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
const b
处的 Promise 构造,同步执行其中的(resolve, reject)=>{...}
。打印:
其中调用了
resolve
,new Promise
得到的结果 Promise1 resolve 。resolved Promise1 的
then
会将其回调直接加入任务队列: 任务1()=>{console.log("promise2")}
,其返回的 Promise1_then1(这也是一个 Promise) 状态未定。Promise1_then1 状态未定,其
then
不会向队列加入任务。Promise1_then2 同理。Promise1_then2 的
then
调用返回的 Promise1_then3 被赋值给b
2 Promise2 构造,同步执行回调,此时
a
为undefined
,因此打印await b
相当于(不等同)执行了b.then
,并将其回调置为该函数剩余部分,并立即返回。由于
b
没有 resolve ,其then
的回调并不入队。Promise2
赋值给a
3
console.log("end")
,打印4 同步执行技术,任务队列中只有任务1,打印
同时,
Promise1_then1
resolve,其then
的回调(任务2)()=>{console.log("promise3")
入队5 队列中只有任务2,打印
同时,
Promise1_then2
resolve,其then
的回调(任务3)()=>{console.log("promise4")
入队6 队列中只有任务3,打印
同时,
Promise1_then3
,也就是b
resolve,其then
的回调(任务4),await b
之后的部分入队7 队列中只有任务4,此时
console.log(a)
打印a
,为一个 Promiseconsole.log("after1")
打印await a
相当于(不等同)执行了a.then
,并将其回调置为该函数剩余部分,并立即返回。由于
a
并没有 resolve, 其then
的回调不入队8 队列已空,执行结束。