I want to know what happens in this code-snippet with the chain of .then
s with regards to the stack, the WebAPI section and the micro-task queue. I tried it in Loupe but it didn't seem to register the .then
s.
setTimeout(function() {console.log(2)}, 0);
Promise.resolve(1)
.then((value) => {console.log(value)}) //
.then((value) => {console.log(value)}) //
It's the fact that the .then
s have to wait til the previous .then
returns a resolved promise (.then
chaining) that confuses me. I'm not sure how this looks. My guess would be:
The first (and only) time the script is run, it recognises .then
as an asynchronous function returning a promise - so it does that in the WebAPI section. The promise that the first .then
takes (Promise.resolve1
) is synchronous and resolves pretty immediately so the .then
's callback ((value) => {console.log(value)}
) is placed pretty immediately into the micro-task queue. Perhaps the script sees that there is a .then
chain and leaves the rest of them since they all rely on each other.
There's nothing more to look at and 'main'/the script is popped off the stack. Now the callback that had been waiting in the micro-task queue is pushed onto the stack and executed. Great, the callback logs 5 and the callback helps the first .then
to return a fulfilled promise with undefined
as its 'result'. The second .then
is immediately called on this new promise. I'm going to stop here because I don't feel confident.
It would be great to have a step-by-step explanation of what happens, with regard to the call-stack, the WebAPI 'thread' or 'area' and the micro-stack queue.