I am very new to asynchronous Javascript and was studying the async/await feature. I have kind of a basic question about the code attached. When I run the code, I think the async function should wait (because of await keyword) and be put in micro-task queue, thus suspending its execution. So, the call stack should execute the main thread's console.log('first') , then print the output of randomFunction() when call stack is empty and micro-task queue starts executing and finally invoke the callback. So I thought the output should've been first, (the random number) and then second. But to my surprise that isn't the case. Can someone please explain why this happened in a simplified manner ?
function randomFunction() {
//generates a random number and prints it
const number = Math.floor(Math.random() * 100);
console.log(number);
}
async function asyncWithCallback(callback) {
await randomFunction();
callback();
}
function callback() {
console.log('second');
}
asyncWithCallback(callback);
console.log('first');
await first evaluates the expression that follows it, and only then the async function returns (with a promise), suspending the function for later.
So the output of the randomFunction is produced synchronously, and then it proceeds as you describe: "first" is output synchronously as well.
Then the call stack becomes empty and we arrive in the "asynchronous phase": the engine processes the job in the PromiseJob queue, which resumes the async function, which calls callback where "second" is output.