I have this piece of code and I'm struggling to understand why the log order is "1,3,2".
(async () => {
const doSomething = async () => {
console.log("1");
};
await doSomething();
console.log("2");
})();
console.log("3");
Async/await is implemented under the hood with promises. With promises even if a promise resolves immediately the callback within the then is added as a microtask, and the current callstack execution continues. Then once the call stack is completed the microtasks are run.
So the way I read the code, the await keyword before the doSomething() function means that the rest of the code in the function after the await will be wrapped in a then call, giving control back to the caller of the function. Thus "3" should be logged first, so the order should be "3,1,2"?
What is the control flow? What actually happens when the javascript translator comes across an await keyword?