Why “1” is after “b”?
The promise specification states that all promise .then() handlers must be called asynchronously after the call stack has emptied. Thus, both a and b, which are executed synchronously on the call stack will execute before any .then() handlers so 1 will always be after a and b.
Some interesting reading:
- Tasks, microtasks, queues and schedules.
- What is the order of execution in JavaScript promises?
- Writing a JavaScript framework – Execution timing, beyond setTimeout.
There’s some good advice here in the thread “Promises wiggle their way between nextTick and setImmediate“:
I would not recommend relying on the exact execution order of non-chained events. If you want to control the execution order – rearrange the callbacks in a way so that the one that you want to be executed later depends on the one that you want to be executed earlier, or implement a queue (that does the same behind the hood).
In other words, if you depend upon a particular ordering of asynchronous events, then you should actually chain them rather than relying on unspecified scheduling in the implementation.