Let us say we have the following async function –
async function foo(x,y) {
x = x+1
await fetch('some_url')
y = y+1
}
When the function foo encounters await, the execution of foo must be suspended and its context must be removed from the call stack. Because only then the event loop will be able to execute other functions by pushing them to call stack. But when the fetch resolves and returns, y = y+1
still has to be executed. How does the event loop handle that?
On searching online, everywhere I find that when await is encountered, the execution of async function is suspended and the event loop can execute other tasks. But how is that possible ? Because if the context of foo is popped off from the stack (to execute other tasks), how does the event loop know that it has to execute y = y+1
after the fetch resolves.
Please provide any documentation that answers the above question.
2
Answers
Here is how I imagine it. Let me know if this is misleading.
async
functions withawait
are equivalent to functions with callbacks. The following code assumes thatfetch
has a variant with callback parameter. (For the promise-variant, writefetch('some_url').then(callback)
instead.)The stack of closures controls which variables are in scope, and this must also be considered besides the call stack.
When
x = x+1
is executed, the call stack isx
andy
are in scopefoo
function foo
var
statementWhen
z = 1
is executed, the call stack isx
andy
are in scopevar
statementWhen
y = y+1
is executed, the call stack isx
andy
are in scopecallback
function foo
fetch
(native)foo
function foo
var
statementWhen an await is encountered in code (either in an async function or in a module), the awaited expression is executed, while all code that depends on the expression’s value is paused and pushed into the
[microtask queue][1]
. The main thread is then freed for the next task in the event loop. This happens even if the awaited value is an already-resolved promise or not a promise.Read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await