这个 Promise 链保证按这个顺序执行吗? [英] Is this Promise chain guaranteed to execute in this order?

查看:22
本文介绍了这个 Promise 链保证按这个顺序执行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

let p = sleep(50);

p.then(() => console.log('a')).then(() => console.log('c'));
p.then(() => console.log('b')).then(() => console.log('d'));

这是否保证按该顺序打印a、b、c、d"?

Is this guaranteed to print "a, b, c, d" in that order?

据我所知,a"必须在c"之前触发,b"必须在d"之前触发,但除此之外,JS解释器是否可以决定以不同的顺序执行余数?

As far as I can tell, "a" has to fire before "c" and "b" has to fire before "d", but beyond that, can the JS interpreter decide to execute the remainder in a different order?

推荐答案

据我所知,a"必须在c"之前触发,b"必须在d"之前触发

As far as I can tell, "a" has to fire before "c" and "b" has to fire before "d"

是的,对于 certan 来说就这么多了.

Yes, that much for certan.

除此之外,JS解释器能否决定以不同的顺序执行余数?

beyond that, can the JS interpreter decide to execute the remainder in a different order?

取决于您询问的对象,但没有更多保证可以使输出更可预测:

Depends on whom you ask, but no there are more guarantees that make the output more predictable:

  • Promise/A+ 规范还要求所有相应的回调必须按照它们的顺序执行发起对 then 的调用."因此,在您的示例中,这意味着a"必须在b"之前触发,因为回调首先链接到 p.
  • ECMAScript 规范定义了一个用于 promise 回调的作业队列,钉钉下订单(不必要的imo).它符合 Promises/A+,因为a"和b"回调按照它们在承诺完成时设置的顺序排队.这也意味着在a"返回并履行承诺后,它将调度c",而在b"返回并履行承诺后,它将调度d",因此它们的顺序也是确定的(对于同步回调).
  • the Promise/A+ specification also demands that "all respective callbacks must execute in the order of their originating calls to then." So in your example, that means "a" has to fire before "b", because the callback was chained first to p.
  • the ECMAScript specification defines a job queue for promise callbacks, nailing down the order (imo unnecessarily). It conforms to Promises/A+ in that the "a" and "b" callbacks are queued in the order they were set up when the promise fulfills. It also means that after "a" returns and fulfills the promise, it will schedule "c", and after "b" returns and fulfills the promise, it will schedule "d", so their order is determined as well (for synchronous callbacks).

一般来说,不要依赖任何调度算法,如果你需要一个特定的顺序,那就明确说明.

In general, don't rely on any scheduling algorithm, if you require a certain order then make it explicit.

这篇关于这个 Promise 链保证按这个顺序执行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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