In Javascript, there are two types of event loops for async tasks.
First one, is well known one, for example, setTimeout, http request, click event will goes into this category. We can call it "Task event loop".
Second one, is called "Microtasks event loop", it is for Promise.
The execution order is
Call stack --> Microtask queue --> Task event queue
Let's have a look code snippet to better understand the order:
setTimeout(() => { console.log('first setTimeout') }); setTimeout(() => { console.log('second setTimeout') }); // Microtasks Promise.resolve().then(() => { console.log('Promise first then() evaluated successfully'); return Promise.resolve(); }) .then(() => { console.log('Promise second then() evaluated successfully'); test = true; }); console.log('Running ...');
What's you guess the console log order?
The correct order is:
Running ...
Promise first then() evaluated successfully
Promise second then() evaluated successfully
first setTimeout
second setTimeout
Even we put setTimeout before Promise code, but still it get executed after promise.