求帮忙!大佬入!async await搞不懂了!

52 阅读2分钟

刷到了一道面试题,相信不少人可以写出正确的答案

async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    new Promise(function(resolve) {
    console.log('promise1');
    resolve();
}).then(function() {
    console.log('promise2');
    });
}
console.log('script start');

setTimeout(function() {
    console.log('setTimeout');
}, 0)
async1();

new Promise(function(resolve) {
    console.log('promise3');
    resolve();
}).then(function() {
    console.log('promise4');
});

console.log('script end');

答案如下:

script start
async1 start
promise1
promise3
script end
promise2
async1 end
promise4
setTimeout

但是如果对其中的async2函数进行一个小改动,如下

async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    //async2做出如下更改:
    return new Promise(function(resolve) {
    console.log('promise1');
    resolve();
}).then(function() {
    console.log('promise2');
    });
}
console.log('script start');

setTimeout(function() {
    console.log('setTimeout');
}, 0)
async1();

new Promise(function(resolve) {
    console.log('promise3');
    resolve();
}).then(function() {
    console.log('promise4');
});

console.log('script end');

答案就会变成:

script start
async1 start
promise1
promise3
script end
promise2
promise4
async1 end
setTimeout

可以注意到的是, async2 中在 new 前面有 return 的时候是 promise2 --> promise4 --> async1 end new 前面没有 return 的时候是 promise2 --> async1 end --> promise4

之前曾经一度天真的以为async await的题不会再困扰我了,结果遇到这个题又不会了。

先说下我的理解

async中遇到await后,将await下面后面的代码(console.log('async1 end'))推入微任务队列,然后再跳出这个async函数去执行同步代码。

当await后面的async2()完全执行好之后,也就是promise2执行之后,再执行async1 end,然后再执行promise4。

不理解的就是,

为什么加了return之后,执行顺序就发生了变化,

不加return的话,async2是不是就会返回一个状态为fulfilled,成功值为undefined的promise?

加了return的话,调用完then后不也同样返回一个状态为fulfilled,成功值为undefined的promise?

困扰了很久,求大佬指点!