Why await only works in async function in javascript?

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 immediately 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!

async and await are both meta keywords that allow asynchronous code to be written in a way that looks synchronous. An async function tells the compiler ahead of time that the function will be returning a Promise and will not have a value resolved right away. To use await and not block the thread async must be used.

async function f() {
    return await fetch('/api/endpoint');
}

is equivalent to

function f() {
    return new Promise((resolve,reject) => {
        return fetch('/api/endpoint')
        .then(resolve);
    });
}