ES6代码执行顺序面试题

async function async1() {
    console.log("async1 start");
    await async2();
    console.log("async1 end");
    return 'async return';
}

async function async2() {
    console.log("async2");
}

console.log("script start");

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

async1().then(function (message) { console.log(message) });

new Promise(function(resolve) {
    console.log("promise1");
    resolve();
}).then(function() {
    console.log("promise2");
});

console.log("script end")
// 执行同步代码,遇到 setTimeout 将其加入到宏任务队列
script start
// 执行 async1()
async1 start
// 遇到await 执行右侧表达式后让出线程,阻塞后面代码
async2
// 执行 Promise 中的同步代码 将 .then 推入到微任务队列
promise1
// 执行同步代码
script end
// 继续执行 await 后面的代码
// 这里需要注意 async 函数返回的是 Promise 对象
// 将 async1后面的 .then 加入到微任务队列
async1 end
// 执行前一轮添加到微任务队列的代码
promise2
// 后一轮微任务队列的代码
async return
// 开始下一轮evenloop,执行宏任务队列中的任务
setTimeout

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值