I'd like to know the order in which the JavaScript code below is executed and why. In particular, I would like to learn more about the contents of the code that goes into the microtask queue, focusing on step-by-step
var promise = Promise.resolve();
promise = promise.then(function(rtnVal) {
console.log('1');
var promise2 = Promise.resolve();
promise2 = promise2.then(function(rtnVal) {
console.log('2');
});
promise2 = promise2.then(function(rtnVal) {
console.log('3');
});
console.log('4');
});
promise = promise.then(function(rtnVal) {
console.log('5');
var promise2 = Promise.resolve();
promise2 = promise2.then(function(rtnVal) {
console.log('6');
});
promise2 = promise2.then(function(rtnVal) {
console.log('7');
});
console.log('8');
});
console.log('9');
Here's what I did: 9,1,4,2,5,8,3,6,7 ->I'm wondering why it runs in this order`
Some things to be aware of:
thencallbacks (if any) are put on the PromiseJob queuethen()is called (not its callback), the returned promise is always pending, even if thatthen()call is made on a resolved promise. This is because the returned promise can only be resolved by executing the callback that is given to thethenmethod since it determines how the promise will resolve, but which can only execute asynchronously.To ease the analysis, I modified your script to give a name to each promise (
atoi) and to each callback function (a_then, ...), but the logic and output remains the same:Here is a sequence of events that happen during the execution of that code.
atoirepresent the state of the promise with that name:?for pending,Ffor fulfilled.Here we go:
a = Promise.resolve()b = a.then(a_then)a_thenf = b.then(b_then)a_thenconsole.log(9)a_thena_thena_thenconsole.log(1)a_thenc = Promise.resolve()a_thend = c.then(c_then)c_thena_thene = d.then(d_then)c_thena_thenconsole.log(4)c_thena_thenbc_then,b_thenc_thenb_thenc_thenconsole.log(2)b_thenc_thendb_then,d_thenb_thend_thenb_thenconsole.log(5)d_thenb_theng = Promise.resolve()d_thenb_thenh = g.then(g_then)d_then,g_thenb_theni = h.then(h_then)d_then,g_thenb_thenconsole.log(8)d_then,g_thenb_thenfd_then,g_thend_theng_thend_thenconsole.log(3)g_thend_theneg_theng_theng_thenconsole.log(6)g_thenhh.thenh_thenh_thenconsole.log(7)h_theni