Write js like advance level

1 min readAug 22, 2024

Guess the chronology of following promise

const promise = new Promise((resolve, reject) => {
console.log(1);
setTimeout(() => {
console.log("timerStart");
resolve("success");
console.log("timerEnd");
}, 0);
console.log(2);
});

promise.then((res) => {
console.log(res);
});

console.log(4);

Step-by-Step Execution:

Creating the Promise:The promise is created, and the executor function is immediately invoked.console.log(1) runs, printing 1 to the console.Setting a Timeout:setTimeout is scheduled with a delay of 0. Even though the delay is 0, the callback still goes to the callback queue, meaning it will run after the current execution stack is complete.console.log(2) runs next, printing 2 to the console.Promise Resolution:The executor function finishes, and control returns to the main code. The promise is still pending at this point.Console.log(4):console.log(4) runs, printing 4 to the console.Processing the Event Loop:The event loop processes the next task in the queue, which is the setTimeout callback.console.log("timerStart") runs, printing timerStart.The promise is resolved with "success", so the then callback is scheduled to run after the current task finishes.console.log("timerEnd") runs, printing timerEnd.Promise .then() Callback:The then callback runs, printing success to the console.Final Output Order:1
2
4
timerStart
timerEnd
successExplanation:The promise executor runs synchronously, so logs 1 and 2 first.console.log(4) is outside the promise and runs immediately after the executor finishes.The setTimeout callback is delayed until the current execution completes, so "timerStart", "timerEnd", and finally "success" are logged in that order.

--

--

PROFESSOR !!
PROFESSOR !!

Written by PROFESSOR !!

start the journey with me and be a master in js and react to beacome a frontend developer

No responses yet