CodeBlanks Logo Icon CodeBlanks

The await operator

JavaScript course · Intermediate · Lesson 79/134

Learn to wait for a promise's result with await.

What await does

The await operator unwraps a promise and pauses the code until the promise settles. It can be used only inside an async function (or at the top level of an ES module).

async function loadUser() {
  const user = await fetchUser();
  console.log(user);
}

Here fetchUser() returns a promise. await waits for it to settle, then hands the value to the user variable. This lets asynchronous code look synchronous.

Where await works

The await keyword is valid only inside an async function body. Used in a regular function, it throws a syntax error. In ES modules, it can also be used at the top level; this is called 'top-level await'.

// Wrong: await outside async
function bad() {
  const x = await p;
}

The code above fails. To use await, you must make the function async.

Exercise Get a promise result with await

Write async function loadProfile(). Inside it, call fetchProfile() with await and assign the result to a profile variable; then write console.log(profile).

Show example solution
async function loadProfile() {
  const profile = await fetchProfile();
  console.log(profile);
}

Test yourself

  1. Add await

    async function loadUser() {
      const user = ____ fetchUser();
      console.log(user);
    }
    Show answer
    async function loadUser() {
      const user = await fetchUser();
      console.log(user);
    }
  2. What does the following code do?

    function f() {
      const x = await p;
    }
    • The code runs and x gets the promise's value.
    • await p never throws an error.
    • It throws a SyntaxError because the function is not async.
    • p is resolved automatically.
    Show answer

    It throws a SyntaxError because the function is not async. — Correct! await is valid only inside an async function.

  3. Match await scenarios

    await fetchUser()
    waits until the promise settles
    await Promise.resolve(10)
    yields 10 immediately
    await Promise.reject(err)
    throws (needs try/catch)
    await 5
    returns 5 (works even without a promise)

All lessons in Intermediate