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?
Now my question is, why didn't it print Paris after 10 sec?for the same reason you seehey brostraight afterstart- the async calls are not blocking, so the next function invocation occurs immediately.const p1 = new Promise(...withconst p1 = () => new Promise(...(same withp2) and replaceawait p1withawait p1()new Promise()is not delayed. It is executed synchronously (not asynchronously). So you createdp2too earlyconst p1 = new Promise()is exectued beforeconst p2 = new Promise(). You're too obsessed with theawait p1which is not where thesetTimeout()is created. You are looking at the wrong place.