当前位置:主页 > 网页前端 > JavaScript代码 >

JS异步宏队列与微队列原理区别详解

时间:2020-12-07 17:02:29 | 栏目:JavaScript代码 | 点击:

1. 原理图

2. 说明

JS 中用来存储待执行回调函数的队列包含 2 个不同特定的列队

JS 执行时会区别这 2 个队列

下面这个例子可以看出Promise要先于setTimeout执行:

setTimeout(() => { //立即放入宏队列
   console.log('timeout callback1()')
   Promise.resolve(3).then(
    value => { //立即放入微队列
     console.log('Promise onResolved3()', value)
    }
   )
  }, 0)

  setTimeout(() => { //立即放入宏队列
   console.log('timeout callback2()')
  }, 0)

  Promise.resolve(1).then(
   value => { //立即放入微队列
    console.log('Promise onResolved1()', value)
    setTimeout(() => {
     console.log('timeout callback3()', value)
    }, 0)
   }
  )

  Promise.resolve(2).then(
   value => { //立即放入微队列
    console.log('Promise onResolved2()', value)
   }
  )

  // Promise onResolved1() 1
  // Promise onResolved2() 2
  // timeout callback1()
  // Promise onResolved3() 3
  // timeout callback2()
  // timeout callback3() 1

3. 相关题目

代码一:

// 3 7 4 1 2 5
  /*
  宏: []
  微: []
  */
  const first = () => (new Promise((resolve, reject) => {
   console.log(3)
   let p = new Promise((resolve, reject) => {
    console.log(7)
    setTimeout(() => {
     console.log(5)
     resolve(6) //会被忽略,因为会先执行微队列里的resolve(1),此时状态已经改变过了,且状态只能改变一次
    }, 0)
    resolve(1)
   })
   resolve(2)
   p.then((arg) => {
    console.log(arg)
   })
  }))

  first().then((arg) => {
   console.log(arg)
  })
  console.log(4)

代码二:

// 1 7 2 3 8 4 6 5 0   
  setTimeout(() => {
   console.log("0")
  }, 0)
  new Promise((resolve, reject) => {
   console.log("1")
   resolve()
  }).then(() => {
   console.log("2")
   new Promise((resolve, reject) => {
    console.log("3")
    resolve()
   }).then(() => {
    console.log("4")
   }).then(() => {
    console.log("5")
   })
  }).then(() => {
   console.log("6")
  })

  new Promise((resolve, reject) => {
   console.log("7")
   resolve()
  }).then(() => {
   console.log("8")
  })

您可能感兴趣的文章:

相关文章