从面试题谈event loop

// 代码一开始就执行宏任务-宏0

    console.log('script start')

    setTimeout(() => {

      console.log('北歌')

    }, 1 * 2000)

    Promise.resolve()

      .then(function () { // 微1-1

        console.log('promise1')

      })

      .then(function () { // 微1-4 这个then中的会等待上一个then执行完成之后得到其状态才会向Queue注册状态对应的回调,假设上一个then中主动抛错且没有捕获,那就注册的是这个then中的第二个回调了。

        console.log('promise2')

      })

    async function foo () {

      await bar()

      console.log('async1 end') // 微1-2

    }

    foo()

    async function errorFunc () {

      try {

        await Promise.reject('error!!!111')

      } catch (e) {

        // => 从这后面开始所有的代码可以理解为放到异步队列微任务中

        console.log(e) // 微1-3

      }

      console.log('async1')

      return Promise.resolve('async1 success')

    }

    errorFunc().then(res => console.log(res))

    function bar () {

      console.log('async2 end')

    }

    console.log('script end')

    // 第一次执行:

    // 全局一个宏任务执行, 输出同步代码。挂载宏1、微1-1、微1-2、微1-3、微1-4。1-表示属于第一次轮询

    // run: script start、 async2 end、script end

 

    // 第二次执行:

    // 同步代码执行完毕,开始执行异步任务中的微任务对列中的代码

    // 微任务列表:只有一个队列且会在当前轮询一次清空

    // run:

    // 执行微1-1: promise1

    // 执行微1-2: async1 end

    // 执行微1-3: error!!!、async1 。当前异步回调执行完毕才Promise.resolve('async1 success'),然后注册then()中的成功的回调-微1-5

    // 执行微1-4: promise2

    //     执行刚刚注册的微1-5: async1 success

 

    // 第三次执行

    // 开启第二波轮询:执行宏1

    // run: '北歌'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值