I got my head spinning off while learn asynchronous javascript. I have following code in async function:
const promise1 = () => {
return new Promise((resolve, _reject) => {
setTimeout(resolve, 3000);
});
};
const promise2 = () => {
return new Promise((resolve, _reject) => {
setTimeout(resolve, 1000);
});
};
await promise1();
console.log(1);
await promise2();
console.log(2);
It's work as i expect: "Wait for 3 seconds,do something synchronous,then wait 1 seconds and do something also synchronous". But if i change my both constants from anonymous function expression to Promise constructor
const promise3 = new Promise((resolve, _reject) => {
setTimeout(resolve, 3000);
});
const promise4 = new Promise((resolve, _reject) => {
setTimeout(resolve, 1000);
});
and call it as
await promise3;
console.log(3);
await promise4;
console.log(4);
my logic fails - second console.log(3) execute immediatelly without 1 second delay.
But again, if i return to first code and change timeout delay so that first delay will be less than second (i.e. first timeout delay 2000ms and second will be 3000) - second console.log(2) execute after difference time between 3000-2000=1000ms.
Can someone detailed explain how it works? I figure out,that's all about micro and macrotask in event loop, but don't understand, why i got this result.
P.S. I know, that both await can be replaced by:
delay(ms1)
.tnen(() =>{
console.log('some1');
return delay(ms2);
})
.then(() =>{
console.log('some2')
})
Just need to understand deep mechanism of event loop with async\await;