Can You Answer This Senior Level JavaScript Promise Interview Question?
FSMD Fahid Sarker
Senior Software Engineer · September 12, 2024
What is the output of the following code?
Code.javascriptconst 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);
Analysis
It’s not a friendly question for junior JS coders. The core feature of JavaScript is asynchronous programming. The interpreter always executes synchronous code first and then asynchronous code.
For example, in this code:
Code.javascriptconsole.log("start"); const promise1 = new Promise((resolve, reject) => { console.log(1); resolve(2); }); promise1.then((res) => { console.log(res); }); console.log("end");
promise1.then() is an asynchronous function call.
So the output is start
, 1
, end
and 2
.
But in JavaScript, asynchronous tasks are also divided into micro tasks and macro tasks.
We generally divide vehicles into two categories:
-
General vehicles
-
Vehicles for emergency missions. Such as fire trucks and ambulances.
When passing through crowded intersections, we will allow fire trucks and ambulances to pass first. Emergency vehicles have more priorities than other vehicles. Keywords: priorities.
In JavaScript EventLoop, there is also the concept of priority.
-
Tasks with higher priority are called microtasks. Includes:
Promise
,ObjectObserver
,MutationObserver
,process
.nextTick
,async/await
. -
Tasks with lower priority are called macrotasks. Includes:
setTimeout
,setInterval
andXHR
.
In this code snippet:
Code.javascriptconsole.log("start"); setTimeout(() => { console.log("setTimeout"); }); Promise.resolve().then(() => { console.log("resolve"); }); console.log("end");
Although setTimeout
and Promise.resolve()
are completed at the same time, and even the code of setTimeout
is still ahead, but because of its low priority
, the callback function belonging to it is executed later.
OK, now that we have explained the basics, let’s go back to our original question.
To solve this question, we just need to do three steps:
-
Find the synchronization code.
-
Find the microtask code
-
Find the macrotask code
First, execute the synchronization code:
Output 1
, 2
and 4
.
Then execute microtask:
But here is a trap: Since the current promise is still in the pending state, the code in this will not be executed at present.
Then execute macrotask:
And the state of the promise becoming to fulfilled.
Then, with Event Loop, execute the microtask again: