js宏任务微任务输出解析

发布于:2024-05-08 ⋅ 阅读:(25) ⋅ 点赞:(0)

第一种情况

      setTimeout(function () {
        console.log('setTimeout 1') //11 宏任务
        new Promise(function (resolve) {
          console.log('promise 1') //12 同步函数
          resolve()
        }).then(function () {
          console.log('promise then') //13 微任务
        })
      })
      async function async1() {
        console.log('async1 start') //2 函数调用
        await async2()
        console.log('async1 end') //7 等待async2执行完成、宏任务里的所有同步函数完成和正常输出完成后,再次获得执行机会
        await async3()
      }

      async function async2() {
        console.log('async2') //3 函数调用
      }

      async function async3() {
        console.log('async3') //8 函数调用
      }

      console.log('eventLoop')  //1  宏任务
      async1()
      new Promise(function (resolve) {
        console.log('promise 2') //4 遇到async2异步函数,处于等待状态,执行promise里的同步函数
        resolve()
      }).then(function () {
        console.log('promise2 then') //9 执行这个微任务
      })

      new Promise(function (resolve) {
        console.log('promise 4') //5 执行promise里的同步函数
        resolve()
      }).then(function () {
        console.log('promise4 then') //10 按照顺序,执行这个微任务
      })

      console.log('eventLoop end') //6 宏任务里的正常输出

第二种情况

      const init = async () => {
        setTimeout(function () {
          console.log('setTimeout 1') //11 宏任务
          new Promise(function (resolve) {
            console.log('promise 1') //12 同步函数
            resolve()
          }).then(function () {
            console.log('promise then') //13 微任务
          })
        })
        async function async1() {
          console.log('async1 start') //2 函数调用
          await async2()
          console.log('async1 end') //4 等待async2执行完成
          await async3()
        }

        async function async2() {
          console.log('async2') //3 函数调用
        }

        async function async3() {
          console.log('async3') //5 函数调用
        }

        console.log('eventLoop') //1  宏任务
        await async1() // 异步函数async1全部执行完成后才会继续往下走
        new Promise(function (resolve) {
          console.log('promise 2') //6 执行promise里的同步函数
          resolve()
        }).then(function () {
          console.log('promise2 then') //9 执行这个微任务
        })

        new Promise(function (resolve) {
          console.log('promise 4') //7 执行promise里的同步函数
          resolve()
        }).then(function () {
          console.log('promise4 then') //10 按照顺序,执行这个微任务
        })

        console.log('eventLoop end') //8 宏任务里的正常输出
      }
      init()

人工智能学习网站

https://chat.xutongbao.top