Search code examples
javascriptasynchronousasync-await

Why await only works in async function in JavaScript?


Just going through this tutorial, and it baffles me to understand why await only works in async function.

From the tutorial:

As said, await only works inside async function.

From my understanding, async wraps the function return object into a Promise, so the caller can use .then()

async function f() {
  return 1;
}

f().then(alert); // 1

And await just waits for the promise to settle within the async function.

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait till the promise resolves (*)

  alert(result); // "done!"
}

f();

It seems to me their usage are not related, could someone please explain?


Solution

  • Code becomes asynchronous on await - we wouldn't know what to return

    What await does in addition to waiting for the promise to resolve is that it immediately1 returns the code execution to the caller. All code inside the function after await is asynchronous.

    • async is syntatic sugar for returning a promise.
    • If you don't want to return a promise at await, what would be the sane alternative in an asynchronous code?

    Let's look at the following erroneous code to see the problem of the return value:

    function f() {
      // Execution becomes asynchronous after the next line, what do we want to return to the caller?
      let result = await myPromise;
    
      // No point returning string in async code since the caller has already moved forward.
      return "function finished";
    }
    

    We could instead ask another question: why don't we have a synchronous version of await that wouldn't change the code to asynchronous?

    My take on that is that for many good reasons making asynchronous code synchronous has been made difficult by design. For example, it would make it too easy for people to accidentally make their whole application to freeze when waiting for an asynchronous function to return.


    To further illustrate the runtime order with async and await:

    async function f() {
        
      for(var i = 0; i < 1000000; i++); // create some synchronous delay
    
      let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("done!"), 1000)
      });
    
      console.log("message inside f before returning, still synchronous, i = " + i);
    
      // let's await and at the same time return the promise to the caller
      let result = await promise;
      console.log("message inside f after await, asynchronous now");
    
      console.log(result); // "done!"
    
      return "function finished";
    }
    
    let myresult = f();
    console.log("message outside f, immediately after calling f");
    

    The console log output is:

    message inside f before returning, still synchronous, i = 1000000 
    message message outside f, immediately after calling f 
    message inside f after await, asynchronous now 
    done!
    

    1 Correction about the immediateness: it returns the code execution to the caller once it gets a promise from the thing that's being awaited. This happens either when somewhere higher up in the call chain a promise is explicitly awaited or an awaited async function returns.

    Thus

    const xxx = async () => { /* when this returns, the call chain becomes async */ }
    const xx = async () => {
        /* synchronous delay can be created here to make a point */
        console.log("inside before");
        await xxx();
        console.log("inside after")
    }
    const x = async () => await xx();
    x();
    console.log("outside");
    

    prints

    inside before
    outside
    inside after