Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In promises, is the callback order guaranteed?

I would like to confirm if the call order of callbacks that are passed to then is guaranteed when there are several callbacks on the same promise.

This is what I observe. Example:

function wait(delayMs) {
    return new Promise(resolve => setTimeout(resolve, delayMs))
}

let prom = wait(500)

for (let i = 0; i < 20; ++i)
    prom.then(() => { console.log(i) }) // OK: Display 0 to 19 in the right order

I observe that the callback order is respected, but I didn't find any documentation on this subject. Is the callback order guaranteed?

EDIT: It is not a question about how to chain promises. Here I have only one promise with several callbacks. The callbacks are passed to then in a determined order. I would like to know if the order of the callback execution is determined too.

like image 401
Paleo Avatar asked Dec 23 '22 20:12

Paleo


1 Answers

If you call "then" on the same promise multiple times (no chaining), the resolver functions will be called in the same order they were added.

The ECMAScript 2015 specs state that "reactions" are enqueued in insertion order if a promise is resolved.

http://www.ecma-international.org/ecma-262/6.0/#sec-triggerpromisereactions

25.4.1.8 TriggerPromiseReactions ( reactions, argument )

The abstract operation TriggerPromiseReactions takes a collection of PromiseReactionRecords and enqueues a new Job for each record. Each such Job processes the [[Handler]] of the PromiseReactionRecord, and if the [[Handler]] is a function calls it passing the given argument.

  1. Repeat for each reaction in reactions, in original insertion order

    a. Perform EnqueueJob("PromiseJobs", PromiseReactionJob, «‍reaction, argument»).

This means that your resolver functions will be called in the order they were added (in your case, from 0 to 19).

like image 129
tcooc Avatar answered Dec 31 '22 14:12

tcooc