1

Here I have written 3 console.log(). Please help me, why Promise is executed before setTimeout even if it has 0 second delay. As per my understanding both setTimeout and Promise are executed in webAPI not in JavaScript Engine. Is this thing is related to priorty?

setTimeout(()=>console.log("SET TIME OUT"),0);  // #1

var promise = new Promise((resolve,reject)=>{
    resolve()
})
promise
    .then(()=>console.log("PROMISE"))          // #2
    .catch((err) => console.log(err))

console.log("SIMPLE CONSOLE LOG");             // #3

OutPut :

SIMPLE CONSOLE LOG
PROMISE
SET TIME OUT
Rahul Singh
  • 184
  • 6

1 Answers1

3

The Promise execution happens as part of the microtask queue processing phase.

When you have a setTimeout function callback scheduled, that function is added to the event loop's macrotask queue and executed when the last running code in the main execution context stack is finished. Then on the next tick of the event loop the task/function is de-queued from the event loop macrotask queue and executed by the JavaScript engine.

But in case of Promise, if there is Promise task queued, that will be set in a microtask queue. Which is executed after all the code in the main execution context stack is done and before the next tick of the event loop happens. The next task from the macrotask queue is only picked up when the tasks in the microtask queue is completely exhausted.

It doesn't matter if you have the setTimeout callback scheduled at 0 milisecond. The priority is such that before the tasks in the macrotask queue is de-queued for processing in the next tick of the event loop, the microtask queue will be processed before that.

Some examples of asynchronous tasks which are queued in the macrotask queue:

setTimeout, setInterval, setImmediate, I/O tasks

Examples of asynchronous tasks in microtask queue:

process.nextTick (node), Promise API

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44