Promise 和 async await 的问题,下面代码打印什么呢?需要解释

let a;
const b = new Promise((resolve, reject) => {
    console.log('promise1');
    resolve();
}).then(() => {
    console.log('promise2');
}).then(() => {
    console.log('promise3');
}).then(() => {
    console.log('promise4');
});

a = new Promise(async(resolve, reject) => {
    console.log(a);
    await b; 
    console.log(a);
    console.log('after1');
    await a
    resolve(true);
    console.log('after2');
});

console.log('end');
阅读 1.2k
1 个回答
let a;
const b = new Promise((resolve, reject) => { // Promise1
    console.log('promise1');
    resolve();
}).then(() => { // Promise1_then1
    console.log('promise2');
}).then(() => { // Promise1_then2
    console.log('promise3');
}).then(() => { // Promise1_then3 === b
    console.log('promise4');
});

a = new Promise(async(resolve, reject) => { // Promise2 === a
    console.log(a);
    await b; 
    console.log(a);
    console.log('after1');
    await a
    resolve(true);
    console.log('after2');
});

console.log('end');

1 const b 处的 Promise 构造,同步执行其中的(resolve, reject)=>{...}
打印:

promise1

其中调用了 resolvenew Promise 得到的结果 Promise1 resolve 。
resolved Promise1then 会将其回调直接加入任务队列: 任务1 ()=>{console.log("promise2")},其返回的 Promise1_then1(这也是一个 Promise) 状态未定。
Promise1_then1 状态未定,其 then 不会向队列加入任务。Promise1_then2 同理。
Promise1_then2then 调用返回的 Promise1_then3 被赋值给 b

2 Promise2 构造,同步执行回调,此时 aundefined,因此打印

undefined

await b 相当于(不等同)执行了 b.then ,并将其回调置为该函数剩余部分,并立即返回。

由于 b 没有 resolve ,其then的回调并不入队。

Promise2 赋值给 a

3 console.log("end"),打印

end

4 同步执行技术,任务队列中只有任务1,打印

promise2

同时,Promise1_then1 resolve,其then的回调(任务2)()=>{console.log("promise3") 入队

5 队列中只有任务2,打印

promise3

同时,Promise1_then2 resolve,其then的回调(任务3)()=>{console.log("promise4") 入队

6 队列中只有任务3,打印

promise4

同时,Promise1_then3,也就是 b resolve,其then的回调(任务4),await b 之后的部分入队

7 队列中只有任务4,此时 console.log(a) 打印 a,为一个 Promise

Promise

console.log("after1") 打印

after1

await a 相当于(不等同)执行了 a.then ,并将其回调置为该函数剩余部分,并立即返回。

由于 a 并没有 resolve, 其then的回调不入队

8 队列已空,执行结束。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题