const p1 = new Promise((resolve,reject) => {
setTimeout(()=>{
resolve("xxx");
}, 5000)
});
const p2 = new Promise((resolve,reject) => {
setTimeout(()=>{
resolve("xx");
}, 10000)
});
async function he() {
console.log("start");
const s1 = await p1;
console.log("Rome");
const s2 = await p2;
console.log("Paris");
}
he();
console.log("Hey bro")
Question – Now when program execution starts, it prints "start" and then "hey bro" instantly and JS does not wait the await to finish and continue with the execution. Now when JS encounters p1 in he(), it prints "Rome" after 5 sec , and then after next 5 sec, it prints Paris.
Now my question is, why didn’t it print Paris after 10 sec? How did the timer start of p2 even before it reached p2 initialization? or did it? I know that when it encounters p1 it halts the execution of he() func in callstack, is this the time where it starts executing s2 behind the scenes somehow?
2
Answers
Because it is asynchronous, and you’re not
await
inghe()
. You can’tawait
at the top level, but if you nest the whole program in anasync
function you canawait
he()
and see it behave as I believe you are expecting.Furthermore, it is worth noting that you are not calling
p1
andp2
– they are promises that start counting down the moment you assign them, so even if you didn’t callhe()
, they would resolve at5
and10
seconds after they were initialized and assigned.It didn’t start when you did this:
It started when you did this:
That is, both timers/promises started immediately. All you’re doing in the
he
function is awaiting the results of those promises, but they’ve already started.The first timer was 5 seconds, the second was 10 seconds. They start at the same time and run simultaneously.
You could achieve the result you’re looking for by not defining the promises until you want to await them. For example:
Or by defining functions which create/return the promises instead of defining the promises themselves: