Promise.then Workflow

The spectrum says (paragraph 5):

PendingJob entries from the same job queue are always triggered in the FIFO order. This specification does not specify the order in which multiple job queues are served. An ECMAScript implementation can interlace the FIFO score of PendingJob records in a Job Queue with the score of PendingJob records in one or more other operation queues.

Does this mean that I can’t expect the callback passed to .then to be evaluated before the callback passed to setTimeout otherwise the synchronous control flow?

In other words, can I depend on the next print of one two .

 setTimeout(() => console.log('two')); Promise.resolve().then(() => console.log('one')); 
+2
javascript promise
source share
3 answers

Does this mean that I cannot count on a callback that was .then evaluated before the callback will setTimeout to setTimeout in an otherwise synchronous control flow?

Yes, what does it mean; specification does not require implementations to work that way.

But in practice, the Promise enabled implementations that I tested planned then callback ("microtask" from the PendingJobs queue) immediately after the completion of the "macrotask" that scheduled it before other pending macros, even if the pending macros were scheduled before the microtask. ( setTimeout and events are macro-saved.)

For example, in those environments where I tested it, this gives reliable results A , C , B :

 console.log("A"); setTimeout(_ => console.log("B"), 0); Promise.resolve().then(_ => console.log("C")); 

But the JavaScript specification does not require this.

As Bergi notes, for user agent environments, the HTML5 specification covers this in its specifications for microcurrents and macro tasks. But this only applies to user agent environments (e.g., browsers).

For example, Node does not fulfill this specification specification (not least because its timer functions return objects, not numbers), but Node also gives us A , C , B above because (thanks to Benjamin Grunbaum!) It fulfills the promises with permission after nextTick but before any nextTick timer or I / O. See its essence for details.

+4
source share

Yes, this is what it means - another event may occur before the promise callback.

No, this will not happen - while ECMAScript allows this, the setTimeout spec does not.

+2
source share

setTimeout does not mean that the delivered function will be executed after the set time. It adds a function to the end of the queue after the expiration of the delay.

It really depends on when your promise decides to fulfill the two statements. In your example, setTimeout will add a callback to the queue before the promised promise, so you can expect one two .

0
source share

All Articles