宏任务 微任务 是什么

198 阅读1分钟

小例题:

console.log(1)

setTimeout(function() {
	console.log(2)
}, 0)

console.log(3)

宏任务: 主线程代码, setTimeout 等属于宏任务, 上一个宏任务执行完, 才会考虑执行下一个宏任务

微任务: promise .then .catch的需要执行的内容, 属于微任务, 满足条件的微任务, 会被添加到当前宏任务的最后去执行

image-20201208040306978.png

事件循环队列 eventLoop

image-20201208040235602.png

例题1:

  console.log(1)

  setTimeout(function() {
    console.log(2) // 宏任务
  }, 0)

  const p = new Promise((resolve, reject) => {
    resolve(1000)
  })
  p.then(data => {
    console.log(data)  // 微任务
  })

  console.log(3)

image-20210306151137688.png

例题2:

async function fn () {
  console.log(111)
}
fn()
console.log(222)

例题3:

async function fn () {
  const res = await 2
  console.log(res)
}
fn()
console.log(222

例题4:

async function fn () {
  console.log('嘿嘿')
  const res = await fn2()
  console.log(res)  // 微任务
}
async function fn2 () {
  console.log('gaga')
}
fn()
console.log(222)

image-20210306152010989.png

考察点: async 函数只有从 await 往下才是异步的开始