节点 Promises 如何介于 `nextTick` 和 `setImmediate` 之间?
How are node Promises getting in between `nextTick` and `setImmediate`?
我的应用程序中有一个奇怪的计时错误,该错误来自从 Bluebird 切换到本机承诺。我修复了它,但留下了这个奇怪的东西:原生承诺似乎在 nextTick
和 setImmediate
之间摇摆不定 - 怎么办?这应该发生吗?关于这些,应该 的承诺在哪里?
~function(){
setTimeout (console.log.bind(console, 'timeout A'));
process.nextTick (console.log.bind(console, 'nextTick A'));
setImmediate (console.log.bind(console, 'setImmediate A'));
Promise.resolve().then(console.log.bind(console, 'promise'));
process.nextTick (console.log.bind(console, 'nextTick B'));
setImmediate (console.log.bind(console, 'setImmediate B'));
setTimeout (console.log.bind(console, 'timeout B'));
}();
本地收益率:
nextTick A
nextTick B
promise undefined
setImmediate A
setImmediate B
timeout A
timeout B
蓝鸟产量:
nextTick A
nextTick B
setImmediate A
promise undefined
setImmediate B
timeout A
timeout B
Native promises seem to wiggle their way in between nextTick and setImmediate -- how? And is this supposed to happen? Where are promises supposed to go with regard to these?
是的,承诺 运行 在微任务 nextTick 队列之后和任何任务(如 setImmediate)执行之前。
这是他们的预期行为,也是我们希望他们在 NodeJS 中执行的操作。这是 decided here and you can read about it here
Bluebird's different behavior
Bluebird 的行为早于原生承诺,bluebird 3.0 使用 nextTick 和微任务语义进行调度。 Bluebird 允许您使用 Promise.setScheduler
和 nextTick
作为调度程序(而不是 setImmediate)手动覆盖此行为。
可以看到the code here:
GlobalSetImmediate.call(global, fn)
请注意,您的代码无论如何都不应该依赖于这些行为。
我的应用程序中有一个奇怪的计时错误,该错误来自从 Bluebird 切换到本机承诺。我修复了它,但留下了这个奇怪的东西:原生承诺似乎在 nextTick
和 setImmediate
之间摇摆不定 - 怎么办?这应该发生吗?关于这些,应该 的承诺在哪里?
~function(){
setTimeout (console.log.bind(console, 'timeout A'));
process.nextTick (console.log.bind(console, 'nextTick A'));
setImmediate (console.log.bind(console, 'setImmediate A'));
Promise.resolve().then(console.log.bind(console, 'promise'));
process.nextTick (console.log.bind(console, 'nextTick B'));
setImmediate (console.log.bind(console, 'setImmediate B'));
setTimeout (console.log.bind(console, 'timeout B'));
}();
本地收益率:
nextTick A
nextTick B
promise undefined
setImmediate A
setImmediate B
timeout A
timeout B
蓝鸟产量:
nextTick A
nextTick B
setImmediate A
promise undefined
setImmediate B
timeout A
timeout B
Native promises seem to wiggle their way in between nextTick and setImmediate -- how? And is this supposed to happen? Where are promises supposed to go with regard to these?
是的,承诺 运行 在微任务 nextTick 队列之后和任何任务(如 setImmediate)执行之前。
这是他们的预期行为,也是我们希望他们在 NodeJS 中执行的操作。这是 decided here and you can read about it here
Bluebird's different behavior
Bluebird 的行为早于原生承诺,bluebird 3.0 使用 nextTick 和微任务语义进行调度。 Bluebird 允许您使用 Promise.setScheduler
和 nextTick
作为调度程序(而不是 setImmediate)手动覆盖此行为。
可以看到the code here:
GlobalSetImmediate.call(global, fn)
请注意,您的代码无论如何都不应该依赖于这些行为。