Explaining the workings of asynchronous calls:
If we look at the code execution:
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");
Inside the 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 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
However, the async function operates asynchronously. So all async calls are placed in a queue for later processing.
Initially, the synchronous calls are executed:
console.log("A");
console.log("D");
Followed by the async calls.
The await
functionality only functions within an async
function.
Therefore, the function:
async function asyncFunc() {
console.log("A");
await delay(1000);
console.log("B");
}
Is essentially equivalent to this:
asyncFunc() {
console.log('A');
delay().then(()=> {
console.log('B');
});
}
If you wish to have the console.log("D") execute after the async function, you must await the asyncFunction. However, using await requires being within an async function:
async function asyncFunc2() {
await asyncAwait();
console.log("D");
}
asyncFunc2();