Is this Promise Chain guaranteed to run in that order?

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')); 

Is printing a, b, c, d guaranteed in that order?

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

+6
javascript promise
source share
2 answers

The way things are queued using setTimeout is exactly the same as the queue. If two callbacks are queued with the same β€œdelay”, the queue that was queued will be executed first.

Edit: I did not understand the original intention of OP.

The 'branching' promises are what really happens here. The value is then-capable, which is referenced in the first set of then-ables (for a and b), the two provided callbacks are triggered at the same time, because they both refer to the same promise, however, the hard bit is that they are executed in the order in which they were queued using the .then(...) object of the enabling promise.

Then the next / subsequent callbacks are queued in their respective orders (c and d).

To answer the question directly: None. The nature of asynchronous actions in that case could be anything. However, the features provided in OP-ables are essentially synchronous, which leads to an intuitive, but completely misleading logging order.

+1
source share

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

Yes, so much for certan.

besides this, can the JS interpreter decide to execute the remainder in a different order?

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

  • The Promise / A + specification also requires that "all relevant callbacks be performed in the order of their outgoing calls." So in your example, this means that "a" should fire before "b" because the callback was bound to p .
  • The ECMAScript specification defines the job queue for callbacks promises, nesting the order (imo unnecessarily). It corresponds to Promises / A + in that the callbacks "a" and "b" are queued in the order in which they were configured when the promise is executed. This also means that after β€œa” returns and fulfills this promise, he will pay β€œc”, and after β€œb” returns and fulfills the promise, he will schedule β€œd”, so their order is also determined (for synchronous inverse calls).

In general, do not rely on any planning algorithm, if you need a certain order, then make it explicit.

+1
source share

All Articles