I read about async/await
, but I've a critical question.
At first I explain an old example to show base of my question and then I ask my exact question.
Everybody know it:
console.log('1');
console.log('2');
console.log('3'); // Ex: 123
It is simple but in below case:
console.log('1');
setTimeout(()=>{
console.log('2');
},0);
console.log('3'); // Ex: 132
It is simple too, setTimeout
function is asynchronous
and JavaScript
jump from it and after resolve run its function, so we see 2
after 1
and 3
.
But, now I read async/await
and I wrote a function like this:
(async function test() {
console.log('1');
await setTimeout(()=>{
console.log('2');
},0);
console.log('3');
})(); // Ex: 132
The Export is 132
too, why? this is my question, why 3
run before 2
? I expect because of async/await
after 1
JavaScript wait for 2
and then wrote 3
. why 132
?
await
only suspends when the value passed to it is a Promise
. In your case, setTimeout
returns a Number
so await doesn't wait for it.
The correct code will be as follows:
async function test() {
console.log('1');
await new Promise((resolve, reject) => {
setTimeout(() => {
console.log('2');
resolve()
}, 0);
});
console.log('3');
}