async and await

Async returns a promise

An async function always returns a promise, even when the body returns a plain value. TypeScript shows this in the return type as Promise around the value type. Callers can await it or chain it like any other promise.

async function getNumber(): Promise<number> { return 1; } const p: Promise<number> = getNumber(); p.then((n: number) => { console.log(n); });

1

Pause for one

Await pauses only the current async function until one promise settles. Other work on the event loop keeps moving meanwhile. The result comes back as a plain typed value. The getNumber helper is repeated here, so the block runs on its own.

async function getNumber(): Promise<number> { return 1; } async function run(): Promise<void> { const n: number = await getNumber(); console.log(n); } run();

1

Try around await

A rejected awaited promise throws at the await point. Wrap the await in try and catch to handle that spot. Keep the try block small so only one risky call can fail there. The program hands safeRun two loaders, one that fulfils and one that rejects, so both branches print.

async function getNumber(): Promise<number> { return 1; } async function failing(): Promise<number> { throw new Error("not ready"); } async function safeRun(load: () => Promise<number>): Promise<void> { try { const n = await load(); console.log(n); } catch (err: unknown) { console.log((err as Error).message); } } safeRun(getNumber); safeRun(failing);

1
not ready

Await in loops

Await inside a for loop runs items one after another in order. This serial style is simple and kind to rate limits. Use it when each step must finish before the next begins. The helper takes the id and returns ten times it, so the output shows the order.

async function getNumber(id: number): Promise<number> { return id * 10; } async function loadAll(ids: number[]): Promise<void> { for (const id of ids) { const n = await getNumber(id); console.log(id, n); } } loadAll([1, 2, 3]);

1 10
2 20
3 30

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an async function return?

    Answer

    A promise, even when the body returns a plain value

    An async function always wraps its result in a promise, so a body with return 1 gives Promise<number>.

  2. What does await pause?

    Answer

    Only the current async function, until the promise settles

    Other tasks keep running on the event loop while the async function waits for its promise.

  3. What does a rejected awaited promise do inside a try block?

    Answer

    It throws at the await point, so catch takes it

    An await turns a rejection into a throw at that line, which is why a small try around it can recover.

  4. What must the return type of an async function be?

    Answer

    A Promise around the type of the returned value

    The caller receives a promise, so the annotation names the value type inside Promise, as Promise<number>.

  5. What does this program print? async function getNumber(): Promise<number> { return 1; } const p: Promise<number> = getNumber(); p.then((n: number) => { console.log(n); });

    Answer

    1

    The promise fulfils with 1 and the callback in then prints that number.

  6. What does this program print? async function failing(): Promise<number> { throw new Error("not ready"); } async function safeRun(load: () => Promise<number>): Promise<void> { try { const n = await load(); console.log(n); } catch (err: unknown) { console.log((err as Error).message); } } safeRun(failing);

    Answer

    not ready

    The rejected await throws inside the try, and the catch prints the message of the error.

  7. What does this program print? async function getNumber(id: number): Promise<number> { return id * 10; } async function loadAll(ids: number[]): Promise<void> { for (const id of ids) { const n = await getNumber(id); console.log(id, n); } } loadAll([1, 2]);

    Answer

    1 10 / 2 20

    The loop awaits each call before it starts the next one, so the pairs print in the order of the list.

  8. What does this program print? async function getNumber(): Promise<number> { return 1; } console.log(getNumber());

    Answer

    Promise { 1 }

    Without await the value is still a promise, and Node prints the promise with its settled value inside.

  9. What does the compiler say about this program? async function f(): number { return 1; } console.log(f());

    Answer

    error TS1064: The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<number>'?

    An async function always returns a promise, so the compiler asks for Promise<number> rather than number.

  10. What does this program print? async function getNumber(): Promise<number> { return 7; } async function run(): Promise<void> { const a = await getNumber(); const b = await getNumber(); console.log(a + b); } run();

    Answer

    14

    Each await waits for one value of 7, and the sum of the two is printed.

Article author: Arthur Isaev