It is how asynchronous calls work.
What you think the code execution is like:
function delay(ms: number) {
return new Promise<void>(function(resolve) {
setTimeout(resolve, ms);
});
}
async function asyncAwait() {
console.log("A");
await delay(1000);
console.log("B");
await delay(1000);
console.log("C");
}
asyncAwait(); // <-- 1st call
console.log("D");
Then inside that function:
async function asyncAwait() {
console.log("A"); // <--- 1st print, as it is synchronous
await delay(1000); // <--- await
console.log("B"); // <--- 2nd print
await delay(1000); // <-- await
console.log("C"); // <-- 3rd print
}
And then finally
function delay(ms: number) {
return new Promise<void>(function(resolve) {
setTimeout(resolve, ms);
});
}
async function asyncAwait() {
console.log("A");
await delay(1000);
console.log("B");
await delay(1000);
console.log("C");
}
asyncAwait();
console.log("D"); // <-- last print
BUT, the async function is asynchronous. So all the async calls go into the queue and are processed later.
Hence, first the synchronous calls are executed:
console.log("A");
console.log("D");
And then the async calls.
The await only works inside an async function.
So the function:
async function asyncFunc() {
console.log("A");
await delay(1000);
console.log("B");
}
is roughly equivalent to this:
asyncFunc() {
console.log('A');
delay().then(()=> {
console.log('B');
});
}
So if you want the console.log("D") to be executed after the async function you should await the asyncFunction. But to use await, you have to be in a async function:
async function asyncFunc2() {
await asyncAwait();
console.log("D");
}
asyncFunc2();
delayPromise and theasyncAwaitfunction with Promise functionality