I'd like to understand the execution order of the following snippet that uses JavaScript promises.
Promise.resolve('A')
.then(function(a){console.log(2, a); return 'B';})
.then(function(a){
Promise.resolve('C')
.then(function(a){console.log(7, a);})
.then(function(a){console.log(8, a);});
console.log(3, a);
return a;})
.then(function(a){
Promise.resolve('D')
.then(function(a){console.log(9, a);})
.then(function(a){console.log(10, a);});
console.log(4, a);})
.then(function(a){
console.log(5, a);});
console.log(1);
setTimeout(function(){console.log(6)},0);
The result is:
1
2 "A"
3 "B"
7 "C"
4 "B"
8 undefined
9 "D"
5 undefined
10 undefined
6
I'm curious about the execution order 1 2 3 7... not the values "A"
, "B"
...
My understanding is that if a promise is resolved the then
function is put in the browser event queue. So my expectation was 1 2 3 4 ...
Why isn't 1 2 3 4 ... the logged order?