宏任务微任务是什么

  1. 宏任务: 主线程要执行的代码, 定时器/延时器 等都属于宏任务, 上一个宏任务执行完, 才会考虑执行下一个宏任务
  2. 微任务: promise .then和 .catch中需要执行的内容, 属于微任务, 满足条件的微任务, 会在当前宏任务执行完,在下一个宏任务开始前执行
  3. 事件循环队列eventLoop

js是单线程的,如果执行时遇到异步内容,就会交给浏览器处理,浏览器是多线程的,可以处理多件事情,满足条件的,将需要执行的内容放到任务队列里进行排队,只有主线程空闲了,才会考虑任务队列的代码

注意:Promise本身是同步的,他的then方法和catch方法是异步的

console.log(1) // 宏任务1的内容
  console.log(1) // 宏任务1的内容
  setTimeout(function () {
    console.log(2) // 宏任务2的内容
    console.log(2) // 宏任务2的内容
    console.log(2) // 宏任务2的内容
  }, 0
  setTimeout(function () {
    console.log(4) // 宏任务3的内容
    console.log(4) // 宏任务3的内容
    console.log(4) // 宏任务3的内容
  }, 0
  console.log(3) // 宏任务1的内容
console.log(1) // 宏任务1的内容

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

  setTimeout(function() {
    console.log(500) // 宏任务3的内容
  }, 1000)

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

  console.log(3) // 宏任务1的内容              1  3  1000  2  500
  
//async 可以用于修饰一个函数, 表示一个函数是异步的
//async 只有在遇到了 await, 才是异步的开始,async 函数只有从 await 往下才是异步的开始
 async function fn () {
   console.log(111)
 }
 fn()
 console.log(222)              //111  222
async function fn () {
   // await开始往下的内容, 就可以理解为, 写在.then的内容
   console.log(3333)
   const res = await 1
   console.log(res)
 }
 fn()
 console.log(22)      3333 22 1
async function fn () {
    console.log('嘿嘿')
    const res = await fn2()
    console.log(res)
  }
  async function fn2 () {
    console.log('gaga')
    //return 100
  }
  fn()
  console.log(222)         //嘿嘿 gaga 222 undefined(因为fn没有返回值,有了return 100,才是嘿嘿 gaga 222  100)
  
posted @ 2022-08-23 22:39  fionna  阅读(132)  评论(0编辑  收藏  举报