Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

求解下方这段 Promise 输出结果 #3

Open
shiiiiiiji opened this issue May 25, 2021 · 1 comment
Open

求解下方这段 Promise 输出结果 #3

shiiiiiiji opened this issue May 25, 2021 · 1 comment

Comments

@shiiiiiiji
Copy link

针对下面这段代码的输出,着实不解。来自于《你不知道的 js》中卷的第 191 页

var p3 = new Promise(function (resolve, reject) {
    resolve("B");
})


var p1 = new Promise(function (resolve, reject) {
    resolve(p3);
})


var p2 = new Promise(function (resolve, reject) {
    resolve("A");
})


p1.then(v => console.log(v));
p2.then(v => console.log(v));
@yygmind
Copy link
Contributor

yygmind commented May 26, 2021

打印顺序是 A、B。
简单理解的话,new Promise() 构造函数是同步执行的,p1.then(v => console.log(v)) 执行后会把异步函数 p3 放到异步队列中等待下次 Event Loop 的执行,而 p2.then(v => console.log(v)) 本次异步任务完成打印 A。
到下一次 Event Loop 会执行 p3 打印 B。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants