节点承诺如何介于“nextTick"和“setImmediate"之间? [英] How are node Promises getting in between `nextTick` and `setImmediate`?

查看:80
本文介绍了节点承诺如何介于“nextTick"和“setImmediate"之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个奇怪的计时错误,原因是从 Bluebird 切换到原生 promise.我修复了它,但留下了这个奇怪的东西:原生承诺似乎在 nextTicksetImmediate 之间摆动——如何?这应该发生吗?与这些相关的 承诺在哪里?

I had a weird timing bug in my app that came from switching from Bluebird to native promises. I fixed it, but am left with this oddity: 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?

~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 似乎在 nextTick 和 setImmediate 之间摆动——如何?这应该发生吗?与这些相关的承诺应该去哪里?

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?

是的,promise 在微任务 nextTick 队列之后和任何任务(如 setImmediate)执行之前运行.

Yes, promises run after the microtask nextTick queue and before any tasks (like setImmediate) execute.

这是他们的预期行为,也是我们期望他们在 NodeJS 中做的事情.这是在此处决定,您可以阅读这里

This is their intended behavior, and what we expect them to do in NodeJS. This was decided here and you can read about it here

蓝鸟的不同行为

Bluebird 的行为早于原生 promise,bluebird 3.0 使用 nextTick 和微任务语义进行调度.Bluebird 允许您使用 Promise.setSchedulernextTick 作为调度程序(而不是 setImmediate)手动覆盖此行为.

Bluebird's behavior predates native promises, bluebird 3.0 uses nextTick and microtask semantics for scheduling. Bluebird lets you manually override this behavior using Promise.setScheduler with nextTick as the scheduler (instead of setImmediate).

您可以在此处查看代码:

GlobalSetImmediate.call(global, fn)

请注意,您的代码无论如何都不应该依赖于这些行为.

NOTE THAT YOUR CODE SHOULD NOT RELY ON THESE BEHAVIORS ANYWAY.

这篇关于节点承诺如何介于“nextTick"和“setImmediate"之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆