浏览器宏任务和微任务

开始

先上题, 那么,在控制台打印的是什么呢

async function async1 () {
  console.log('async1 start')
  await async2()
  console.log('async1 end')
}
async function async2 () {
  console.log('async2')
  setTimeout(() => {
    console.log('async2 setTimeout')
  },0)
}
console.log('script start')
async1()
setTimeout(() => {
  console.log('setTimeout')
},0)
new Promise((resolve) => {
  console.log('promise1')
  resolve()
}).then(() => {
  console.log('promise2')
})
console.log('script end')

思考

  1. 为什么 setTimeout 最后才打印?

  2. 为什么 async1 endscript end 之后打印?`

宏任务和微任务

  1. 浏览器的宏任务只有俩个: setTimeoutsetInterval

  2. 浏览器的微任务有: 除了上俩个之外的所有 function, 一般用同步方法和异步方法区别

浏览器的执行顺序

首先,明确一个前提, JS 是单线程,所以函数要一个一个排队执行。浏览器会将代码声明按照宏和微划分,执行顺序是 ::: tip 执行顺序 宏任务=> 该宏下微任务 => 下一个宏任务 => 下一个宏所有微 => ... :::

实际执行的代码结构

function async1 () {
  console.log('async1 start')
  return function async2 () {
    return new Promise((resolve) => {
      console.log('async2')
      resolve()
      setTimeout(() => {
        console.log('async2 setTimeout')
      },0)
    }).then(() => {
      console.log('async1 end')
    })
  }
}
console.log('script start')
async1()()
setTimeout(() => {
  console.log('setTimeout')
},0)
new Promise((resolve) => {
  console.log('promise1')
  resolve()
}).then(() => {
  console.log('promise2')
})
console.log('script end')

结果

// 控制台的输出
// script start
// async1 start
// async2
// promise1
// script end
// async1 end
// promise2
// sync2 setTimeout
// setTimeout

参考

Last updated