promise、async/await的执行顺序

先说结论:

  • js总是先执行主线程上的任务,执行完毕后执行当前宏任务队列上的所有微任务,先进先出原则,在执行完这一个宏任务队列上的所有微任务之后,才会继续执行下一个宏任务。
  • promise的构造函数的运行是在主任务队列中的
  • await会阻塞后面的任务,指的是下一行代码,await同行代码是会立即执行的
  • async await实质只是promise.then 的语法糖,带 async 关键字的函数,它使得你的函数的返回值必定是promise 对象,如果async关键字函数返回的不是promise,会自动用Promise.resolve()包装
  • 每当遇到.then函数,其回调是会被放到微任务队列中排队等待执行的,而.then的.then函数更是只有等到前一个微任务中的回调被执行后,才会继续将后续的.then开始放入到微任务队列中

例1:

new Promise((resolve) => {
  console.log(1);
  resolve();
})
  .then(() => {
    console.log(2);
  })
  .then(() => {
    console.log(3);
  });

new Promise((resolve) => {
  console.log(4);
  resolve();
})
  .then(() => {
    console.log(5);
  })
  .then(() => {
    console.log(6);
  });


// 1
// 4
// 2
// 5
// 3
// 6

例2:

async function async1() {
    console.log('async1 start');
    await async2();                
    console.log('async1 end');
}
async function async2() {
    await async3(); 
    console.log('async2');
}
async function async3() {
    console.log('async3');
}
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');

// script start
// async1 start
// async3
// promise1
// script end
// async2
// promise2
// async1 end
// undefined
// setTimeout
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值