As I was exploring the resolution of promises within one another, I came across some intriguing behavior:
const someTask = callback => {
new Promise(res => res())
.then(() => callback())
.then(() => console.log("A 1!"))
.then(() => console.log("A 2!"));
};
new Promise(res => someTask(res))
.then(() => console.log("B 1!"))
.then(() => console.log("B 2!"));
The resulting output is as follows:
B 1!
A 1!
B 2!
A 2!
Based on my initial expectations, I anticipated that:
At minimum, one chain would be executed entirely before moving on to the next so all A's
.then
callbacks would run first followed by B's, or vice versa. However, they appear to alternate back and forth rather than executing in sequence.A's initial log statement would occur before B's since it resolved first.
I acknowledge that this may vary depending on implementation and that I shouldn't rely on execution order (my main concern in my project is ensuring A resolves B when necessary), but I am intrigued by the reasons behind this behavior. This applies to both native promises and Bluebird, with no difference in the outcome.