Execute Program

Everyday TypeScript: Async Await

Welcome to the Async Await lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • JavaScript's async/await syntax lets us use promises, but with a more natural syntax. Like promises, async/await fits nicely into TypeScript's type system. When we await a Promise<T>, we get a value of type T.

  • (Note that async functions always return promises. All of the examples in this lesson result in promises, which Execute Program represents as {fulfilled: theValueHere}.)

  • >
    async function returns5() {
    const aPromise = Promise.resolve(5);
    const aNumber: number = await aPromise;
    return aNumber;
    }

    returns5();
    Asynchronous Icon Async Result:
  • Async functions must have a return type of Promise<T>. This makes sense if we think about it: an async function always returns a promise. If we give our async function a non-promise return type, that's a type error.

  • >
    async function asyncDouble(x: Promise<number>): Promise<number> {
    return 2 * await x;
    }

    asyncDouble(Promise.resolve(5));
    Asynchronous Icon Async Result:
    {fulfilled: 10}Pass Icon
  • Here's a code problem:

    The async function below has a return type of number. That's a type error: async functions must always have a return type of Promise<SomeOtherType>. Wrap the return type in Promise to fix the type error. (You only need to change the return type; the rest of the function is correct.)

    async function asyncDouble(x: Promise<number>): Promise<number> {
    return 2 * await x;
    }
    asyncDouble(Promise.resolve(5));
    Asynchronous Icon Async Result:
    Goal:
    {fulfilled: 10}
    Yours:
    {fulfilled: 10}Pass Icon