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链按此顺序执行?
发布评论