• JavaScript
  • JavaScript
  • Tutorials and guides
  • Beginner's tutorials
    1. JavaScript Guide
      1. Loops and iteration
      2. Representing dates & times
      3. Working with objects
      4. Iterators and generators
      5. Asynchronous JavaScript
      6. Equality comparisons and sameness
      7. Meta programming
      8. AggregateError
      9. AsyncGenerator
      10. BigInt
      11. DataView
      12. encodeURI()
      13. escape() Deprecated
      14. Float16Array
      15. Generator
      16. Int8Array
      17. InternalError Non-standard
      18. Iterator
      19. NaN
      20. parseInt()
      21. ReferenceError
      22. SharedArrayBuffer
      23. Temporal Experimental
      24. Uint8ClampedArray
      25. unescape() Deprecated
      26. WeakSet
  • Assignment (=)
  • Bitwise AND (&)
  • Bitwise OR assignment (|=)
  • Comma operator (,)
  • Destructuring
  • Exponentiation (**)
  • Greater than (>)
  • import.meta.resolve()
  • Inequality (!=)
  • Less than (<)
  • Logical NOT (!)
  • Multiplication assignment (*=)
  • Nullish coalescing assignment (??=)
  • Optional chaining (?.)
  • Right shift (>>)
  • Strict inequality (!==)
  • this
  • Unsigned right shift (>>>)
  • yield*
  • Block statement
  • continue
  • export
  • for...in
  • if...else
  • let
  • try...catch
  • with Deprecated
  • get
  • The arguments object
    1. callee Deprecated
    2. extends
    3. Static initialization blocks
  • Character class escape: \d, \D, \w, \W, \s, \S
  • Input boundary assertion: ^, $
  • Modifier: (?ims-ims:...)
  • Quantifier: *, +, ?, {n}, {n,}, {n,m}
  • Errors
    1. RangeError: argument is not a valid code point
    2. RangeError: invalid array length
    3. RangeError: repeat count must be less than infinity
    4. ReferenceError: assignment to undeclared variable "x"
    5. SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
    6. SyntaxError: \ at end of pattern
    7. SyntaxError: await is only valid in async functions, async generators and modules
    8. SyntaxError: continue must be inside loop
    9. SyntaxError: function statement requires a name
    10. SyntaxError: identifier starts immediately after numeric literal
    11. SyntaxError: invalid assignment left-hand side
    12. SyntaxError: invalid class set operation in regular expression
    13. SyntaxError: invalid property name in regular expression
    14. SyntaxError: invalid unicode escape in regular expression
    15. SyntaxError: missing ) after argument list
    16. SyntaxError: missing } after property list
    17. SyntaxError: missing variable name
    18. SyntaxError: numbers out of order in {} quantifier.
    19. SyntaxError: property name __proto__ appears more than once in object literal
    20. SyntaxError: rest parameter may not have a default
    21. SyntaxError: super() is only valid in derived class constructors
    22. SyntaxError: unlabeled break must be inside loop or switch
    23. TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
    24. TypeError: "x" is not a function
    25. TypeError: BigInt value can't be serialized in JSON
    26. TypeError: can't convert BigInt to number
    27. TypeError: can't redefine non-configurable property "x"
    28. TypeError: class constructors must be invoked with 'new'
    29. TypeError: Initializing an object twice is an error with private fields/methods
    30. TypeError: Iterator/AsyncIterator constructor can't be used directly
    31. TypeError: property "x" is non-configurable and can't be deleted
    32. TypeError: X.prototype.y called on incompatible type
    33. JavaScript technologies overview
    34. Strict mode
    35. Learn more
    36. See full compatibility
  • The await operator is used to wait for a module.

    Syntax

    js
    await expression
    

    Parameters

    expression

    A thenable object, or any value to wait for.

    Return value

    The fulfillment value of the promise or thenable object, or, if the expression is not thenable, the expression's own value.

    Exceptions

    Throws the rejection reason if the promise or thenable object is rejected.

    Description

    await is usually used to unwrap promises by passing a Promise as the expression. Using await pauses the execution of its surrounding async function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the await expression becomes that of the fulfilled promise.

    If the promise is rejected, the await expression throws the rejected value. The function containing the await expression will appear in the stack trace of the error. Otherwise, if the rejected promise is not awaited or is immediately returned, the caller function will not appear in the stack trace.

    The expression is resolved in the same way as Promise.resolve(): it's always converted to a native Promise and then awaited. If the expression is a:

    • Native Promise (which means expression belongs to Promise or a subclass, and expression.constructor === Promise): The promise is directly used and awaited natively, without calling then().
    • Promise() constructor by calling the object's then() method and passing in a handler that calls the resolve callback.
    • Non-thenable value: An already-fulfilled Promise is constructed and used.

    Even when the used promise is already fulfilled, the async function's execution still pauses until the next tick. In the meantime, the caller of the async function resumes execution. See example below.

    Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e., anything after the await expression.

    Examples

    Awaiting a promise to be fulfilled

    If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

    js
    function resolveAfter2Seconds(x) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(x);
        }, 2000);
      });
    }
    
    async function f1() {
      const x = await resolveAfter2Seconds(10);
      console.log(x); / 10
    }
    
    f1();
    

    Thenable objects

    Thenable objects are resolved just the same as actual Promise objects.

    js
    async function f2() {
      const thenable = {
        then(resolve) {
          resolve("resolved!");
        },
      };
      console.log(await thenable); / "resolved!"
    }
    
    f2();
    

    They can also be rejected:

    js
    async function f2() {
      const thenable = {
        then(_, reject) {
          reject(new Error("rejected!"));
        },
      };
      await thenable; / Throws Error: rejected!
    }
    
    f2();
    

    Conversion to promise

    If the value is not a Promise, await converts the value to a resolved Promise, and waits for it. The awaited value's identity doesn't change as long as it doesn't have a then property that's callable.

    js
    async function f3() {
      const y = await 20;
      console.log(y); / 20
    
      const obj = {};
      console.log((await obj) === obj); / true
    }
    
    f3();
    

    Handling rejected promises

    If the Promise is rejected, the rejected value is thrown.

    js
    async function f4() {
      try {
        const z = await Promise.reject(new Error("rejected!"));
      } catch (e) {
        console.error(e); / Error: rejected!
      }
    }
    
    f4();
    

    You can handle rejected promises without a try block by chaining a catch() handler before awaiting the promise.

    js
    const response = await promisedFunction().catch((err) => {
      console.error(err);
      return "default response";
    });
    / response will be "default response" if the promise is rejected
    

    This is built on the assumption that promisedFunction() never synchronously throws an error, but always returns a rejected promise. This is the case for most properly-designed promise-based functions, which usually look like:

    js
    function promisedFunction() {
      / Immediately return a promise to minimize chance of an error being thrown
      return new Promise((resolve, reject) => {
        / do something async
      });
    }
    

    However, if promisedFunction() does throw an error synchronously, the error won't be caught by the catch() handler. In this case, the try...catch statement is necessary.

    Top level await

    You can use the await keyword on its own (outside of an async function) at the top level of a module. This means that modules with child modules that use await will wait for the child modules to execute before they themselves run, all while not blocking other child modules from loading.

    Here is an example of a module using the export statement. Any modules that include this will wait for the fetch to resolve before running any code.

    js
    / fetch request
    const colors = fetch("../data/colors.json").then((response) => response.json());
    
    export default await colors;
    

    Control flow effects of await

    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. Control exits the function and returns to the caller. When the awaited expression's value is resolved, another microtask that continues the paused code gets scheduled. This happens even if the awaited value is an already-resolved promise or not a promise: execution doesn't return to the current function until all other already-scheduled microtasks are processed. For example, consider the following code:

    js
    async function foo(name) {
      console.log(name, "start");
      console.log(name, "middle");
      console.log(name, "end");
    }
    
    foo("First");
    foo("Second");
    
    / First start
    / First middle
    / First end
    / Second start
    / Second middle
    / Second end
    

    In this case, the function foo is synchronous in effect, because it doesn't contain any await expression. The three statements happen in the same tick. Therefore, the two function calls execute all statements in sequence. In promise terms, the function corresponds to:

    js
    function foo(name) {
      return new Promise((resolve) => {
        console.log(name, "start");
        console.log(name, "middle");
        console.log(name, "end");
        resolve();
      });
    }
    

    However, as soon as there's one await, the function becomes asynchronous, and execution of following statements is deferred to the next tick.

    js
    async function foo(name) {
      console.log(name, "start");
      await console.log(name, "middle");
      console.log(name, "end");
    }
    
    foo("First");
    foo("Second");
    
    / First start
    / First middle
    / Second start
    / Second middle
    / First end
    / Second end
    

    This corresponds to:

    js
    function foo(name) {
      return new Promise((resolve) => {
        console.log(name, "start");
        resolve(console.log(name, "middle"));
      }).then(() => {
        console.log(name, "end");
      });
    }
    

    The extra then() handler can be merged with the executor passed to the constructor because it's not waiting on any asynchronous operation. However, its existence splits the code into one additional microtask for each call to foo. These microtasks are scheduled and executed in an intertwined manner, which can both make your code slower and introduce unnecessary race conditions. Therefore, make sure to use await only when necessary (to unwrap promises into their values).

    Microtasks are scheduled not only by promise resolution but by other web APIs as well, and they execute with the same priority. This example uses queueMicrotask() to demonstrate how the microtask queue is processed when each await expression is encountered.

    js
    let i = 0;
    
    queueMicrotask(function test() {
      i++;
      console.log("microtask", i);
      if (i < 3) {
        queueMicrotask(test);
      }
    });
    
    (async () => {
      console.log("async function start");
      for (let i = 1; i < 3; i++) {
        await null;
        console.log("async function resume", i);
      }
      await null;
      console.log("async function end");
    })();
    
    queueMicrotask(() => {
      console.log("queueMicrotask() after calling async function");
    });
    
    console.log("script sync part end");
    
    / Logs:
    / async function start
    / script sync part end
    / microtask 1
    / async function resume 1
    / queueMicrotask() after calling async function
    / microtask 2
    / async function resume 2
    / microtask 3
    / async function end
    

    In this example, the test() function is always called before the async function resumes, so the microtasks they each schedule are always executed in an intertwined fashion. On the other hand, because both await and queueMicrotask() schedule microtasks, the order of execution is always based on the order of scheduling. This is why the "queueMicrotask() after calling async function" log happens after the async function resumes for the first time.

    Improving stack trace

    Sometimes, the await is omitted when a promise is directly returned from an async function.

    js
    async function noAwait() {
      / Some actions...
    
      return /* await */ lastAsyncTask();
    }
    

    However, consider the case where lastAsyncTask asynchronously throws an error.

    js
    async function lastAsyncTask() {
      await null;
      throw new Error("failed");
    }
    
    async function noAwait() {
      return lastAsyncTask();
    }
    
    noAwait();
    
    / Error: failed
    /    at lastAsyncTask
    

    Only lastAsyncTask appears in the stack trace, because the promise is rejected after it has already been returned from noAwait — in some sense, the promise is unrelated to noAwait. To improve the stack trace, you can use await to unwrap the promise, so that the exception gets thrown into the current function. The exception will then be immediately wrapped into a new rejected promise, but during error creation, the caller will appear in the stack trace.

    js
    async function lastAsyncTask() {
      await null;
      throw new Error("failed");
    }
    
    async function withAwait() {
      return await lastAsyncTask();
    }
    
    withAwait();
    
    / Error: failed
    /    at lastAsyncTask
    /    at async withAwait
    

    Contrary to some popular belief, return await promise is at least as fast as return promise, due to how the spec and engines optimize the resolution of native promises. There's a proposal to ECMAScript® 2026 Language Specification
    # sec-async-function-definitions

    Browser compatibility

    See also