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 typeT.(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();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));Async Result:
{fulfilled: 10}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 ofPromise<SomeOtherType>. Wrap the return type inPromiseto 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));Async Result:
- Goal:
{fulfilled: 10}- Yours:
{fulfilled: 10}