是否保证此Promise链按此顺序执行?

编程入门 行业动态 更新时间:2024-10-26 22:17:17
本文介绍了是否保证此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 +规范还要求"所有各自的回调必须按照其顺序执行".因此,在您的示例中,这意味着"a"必须在"b"之前触发,因为回调首先链接到 p .
  • ECMAScript规范为承诺回调定义了工作队列,下订单(不必要的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链按此顺序执行?

本文发布于:2023-10-18 02:19:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502793.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按此   顺序   Promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!