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

一道字节的异步笔试题,请写出代码的运行结果 #1

Open
litter-fish opened this issue Nov 27, 2021 · 0 comments
Open

Comments

@litter-fish
Copy link
Owner

Advanced-Frontend/Daily-Interview-Question#7

async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}
async function async2() {
    // async 返回一个promise,而不是值
    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

解释:
await - 如果await后面返回了一个具体的值则
如果返回的是一个promise则会将返回值的then加入微任务队列,然后跳出async函数之前其他微任务,等待微任务队列执行完,再次回到async函数执行await后面的代码,所以async1 end会在promise4输出。

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

No branches or pull requests

1 participant