js事件循环,执行顺序的问题

最近在研究事件循环,看到了一篇不错的博文,阅读学习后,对于博主的举的一个例子,有些疑惑,大家帮忙看看!

console.log('1')

setTimeout(function () {
  console.log('2')
  process.nextTick(function () {
    console.log('3')
  })
  new Promise(function (resolve) {
    console.log('4')
    resolve()
  }).then(function () {
    console.log('5')
  })
})

process.nextTick(function () {
  console.log('6')
})
new Promise(function (resolve) {
  console.log('7')
  resolve()
}).then(function () {
  console.log('8')
})

setTimeout(function () {
  console.log('9')
  process.nextTick(function () {
    console.log('10')
  })
  new Promise(function (resolve) {
    console.log('11')
    resolve()
  }).then(function () {
    console.log('12')
  })
})

根据博主的分享,最后输出顺序是 1,7,6,8,2,4,3,5,9,11,10,12
但是我在node中运行里一下,输出顺序是1 7 6 8 2 4 9 11 3 10 5 12

我个人理解的是,在第二轮事件循环的时候,执行setTimeout1, setTimeout2 把其中的微任务,放到一个队列中,setTimeout1,setTimeout2执行完后,执行微任务-----> [process2,then2,process3, then3], 但是输出顺序process3提到了then2前面变成--->
[process2,process3,then2, then3]

阅读 2.2k
2 个回答

看到process.nextTick就不用期望什么顺序了。官方文档解释事件循环已经吧process.nextTick单独拿出来说了

You may have noticed that process.nextTick() was not displayed in the diagram, even though it's a part of the asynchronous API. This is because process.nextTick() is not technically part of the event loop. Instead, the nextTickQueue will be processed after the current operation is completed, regardless of the current phase of the event loop. Here, an operation is defined as a transition from the underlying C/C++ handler, and handling the JavaScript that needs to be executed.

看还是看官方的文档比较妥当

我记得node在某个版本时候改过promise的调度,具体是哪个有点忘了,你可以搜搜看。记得好像是V8的实现问题,当时的chrome貌似也有问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题