前端面试题之事件循环—宏任务和微任务

229 阅读1分钟

宏任务 微任务 是什么

console.log(1)

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

console.log(3)

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

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

image.png

事件循环队列 eventLoop

image.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.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.png

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

总结

什么是宏任务 什么微任务

  • 异步任务分为两种,一种是宏任务 一种是微任务 异步要执行的任务和js处于同一个进程 和js相关的 属于微任务 在一个新的进程 做的事情和js无关的 就是宏任务 (微任务js进程自己可以做 宏任务需要让浏览器找一个外包帮你做)

    • 执行顺序 同步代码 -> 微任务 -> 宏任务 -> 微任务
    • 哪些是微任务 promise,async这些是微任务 其他的是宏任务
    • new Promise() await后面的代码相当写在then里面

setTimeout 秒表在旁边计时

ajax 让浏览器去服务器拿东西

Promise就是js语法 所以它是和js有关系的 微任务