I try to follow the ECMAScript spec to find out how async/await do its work and encountered some hurdle.
Let's suppose there is such code:
function boo() {
return 1;
}
async function foo() {
let result = await boo();
return result;
}
foo();
So let's start to track step by step what must be done under the hood:
Running
[[Call]]internal method offoo(), that suspends the current execution context (callerContext), creates new one (calleeContext) and pushes it onto the execution context stack. We have the execution context stack of this look:callerContext < calleeContext -- running.The next step is a
foo()evaluation (that isAsyncFunctionBodyassociated with it), that in effect isEvaluateAsyncFunctionBody. This routine, in turn, callsAsyncFunctionStart. It creates a copy of the running execution context -asyncContext- and pushes it onto the stack, which now is as follows:callerContext < calleeContext < asyncContext -- running.calleeContextis left anxious to receive the result ofasyncContextevaluation later (step 10).As it was prescribed in
AsyncFunctionStart,asyncContextevaluatesFunctionBodyoffoo(). Theawaitexpression is met along the way. It is defined to get the result ofboo()firstly and subsequently callAwaitroutine with1as an argument.Awaitcreates a promise resolved with1and performs itsthen(), so that the promise can notify of its fulfilled value and this value would exposed as the result of theawaitexpression. But for nowasyncContextis removed from the execution context stack, which at the current time iscallerContext < calleeContext -- running.
It is difficult to me to understand what is next due to happen. A promise takes the opportunity to notify its subscribers only when the execution context stack is empty because for the sake of it the Job queue is involved. In the other hand, caleeContext is waiting for the result of asyncContext evaluation (step 10 of AsyncFunctionStart) and I can't find the place where both execution contexts (calleeContext and callerContext) removed from the stack. It seems like a deadlock!