Reputation: 99
I'm investigating the event loop. But I ran into a question. What works before on eventloop? Microtasks or macrotasks? if I run the following code
Promise.resolve().then(()=> console.log('Promise'));
setTimeOut(()=>console.log("setTimeout"),0);
console.log show "Promise setTimeout"; but according to an answer Difference between microtask and macrotask within an event loop context Macrotasks works before microtask.
Upvotes: 1
Views: 92
Reputation: 14191
Macrotasks
are processed before other microtasks
, but after a macrotask finishes all of the microtasks that are scheduled are going to run. A corollary of this is that 2 macrotasks cannot run one after another if there are some microtasks already scheduled.
Your current JS loop run (where you're running Promise
and setTimeout
) is actually a Macrotask
. Promise
schedules a microtask and setTimeout
a macrotask.
When the current script ends, a Macrotask
ends and the runtime looks into the microtask queue. It resolves the Promise
and, if no other microtasks are scheduled from this run it will run the next Macrotask
. In your case this is the setTimeout
method.
Upvotes: 0