What is the log order of the code above?
Question description
async function async1() {console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {console.log('async2');
}
console.log('script start');
setTimeout(function () {console.log('setTimeout');
}, 0);
async1();
new Promise(function (resolve) {console.log('promise1');
resolve();}).then(function () {console.log('promise2');
});
console.log('script end');
这道题考察 JavaScript 的事件循环、宏任务与微任务执行顺序。代码先同步输出脚本开始和 Promise 构造器中的日志,再执行 async 函数,遇到 await 后会先输出 await 之前的部分并把后续内容放入微任务队列,最后才轮到 setTimeout 这类宏任务。解题关键是分清同步代码、Promise.then 微任务和定时器宏任务的先后关系,从而还原最终打印顺序。
正文完