skip to Main Content

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


  1. Here is how I imagine it. Let me know if this is misleading.

    async functions with await are equivalent to functions with callbacks. The following code assumes that fetch has a variant with callback parameter. (For the promise-variant, write fetch('some_url').then(callback) instead.)

    function foo(x,y) {
      function callback() {
        y = y+1
      }
      x = x+1
      fetch('some_url', callback)
    }
    var x, y, z
    foo(1,2)
    z = 1
    

    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 is

    function which x and y are in scope
    foo the parameters of function foo
    called from main program declared by the var statement

    When z = 1 is executed, the call stack is

    function which x and y are in scope
    main program declared by the var statement

    When y = y+1 is executed, the call stack is

    function which x and y are in scope
    callback the parameters of function foo
    called from fetch (native) none
    called from foo the parameters of function foo
    called from main program declared by the var statement
    Login or Signup to reply.
  2. When 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search