账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    async await 和 promise微任务执行顺序问题
    • 2019-02-20 00:00
    • 10
    28
    0

    问题描述

    今天看到一个关于js执行顺序的问题,不太了解async awite中awite后的代码的执行时机

    • 问题1. 为啥promise2、promise3输出比async1 end输出早?如果都是微任务的话,不是async1 end先加入微任务队列的吗?
    • 问题2. 为什么async1 end又先于promise4输出呢?

    相关代码

    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')
    }).then(function() {
      console.log('promise3')
    }).then(function() {
      console.log('promise4')
    }).then(function() {
      console.log('promise5')
    }).then(function() {
      console.log('promise6')
    }).then(function() {
      console.log('promise7')
    }).then(function() {
      console.log('promise8')
    })
    console.log('script end')

    chrome 70.0.3538.102 结果

    script start
    async1 start
    async2
    promise1
    script end
    promise2 // 与 chrome canary 73 不一致
    promise3 // 与 chrome canary 73 不一致
    async1 end // 与 chrome canary 73 不一致
    promise4
    promise5
    promise6
    promise7
    promise8
    setTimeout

    Chrome canary 73.0.3646.0(同node8.12.0):

    script start
    async1 start
    async2
    promise1
    script end
    async1 end // 与 chrome 70 不一致
    promise2 // 与 chrome 70 不一致
    promise3 // 与 chrome 70 不一致
    promise4
    promise5
    promise6
    promise7
    promise8
    setTimeout
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部