Async/Await: The Restaurant Waiter

Async/Await: The Restaurant Waiter in TypeScript: You take a worn pair of boots to the menders.

The Analogy: The Collection Ticket at a Shoe Repairer's

You take a worn pair of boots to the menders. You do not stand frozen at the counter while the cobbler resoles them, blocking the queue behind you; instead the cobbler hands you a numbered ticket and you walk out to get on with your day. The ticket is not the boots. It is a claim on boots that do not exist in finished form yet, handed to you the instant you drop them off so that you are free rather than stuck. A Promise is that ticket: a stand-in for a value that will be ready later, returned to you at once so nothing has to wait in place.

The ticket lets the rest of your errands proceed. You post letters, buy groceries, collect a prescription, all while the resoling happens in the back room without you watching it. Only when you actually need the boots do you return to the shop, present the ticket at the counter, and wait there -- and only if they are not finished yet. That act of returning, presenting the ticket, and pausing just until the work is done is await: it suspends only the single errand that needs the result, not your whole day, and it hands you the finished value once the claim is honoured.

Presenting the ticket has exactly two outcomes. Either the boots come back resoled, which is the promise resolving with a value, or the cobbler steps out with an apology: the leather had perished, here is your deposit back and a note explaining why. That second outcome is rejection, and it is why collecting a result is wrapped in a try/catch, so the apology has somewhere to be read. You can also drop several tickets at once, boots and a bag and a belt, and decide to collect only when every job is finished, which is Promise.all handing back all the results together in the order you dropped them off.

The failure mode is walking off as though the paper ticket were the boots themselves. If you treat the claim as the finished thing you get nonsense: try to wear the ticket and you have bare feet. A Promise used without await is exactly this -- it is a Promise object, not the value inside it, so reading a field off it gives undefined and doing arithmetic on it gives NaN. The other failure is never returning to collect at all: a promise that rejects with nobody at the counter to catch the apology is an unhandled rejection, an error shouted into an empty shop that crashes the program instead of being read.


Syntax or Core Structure

An async function always returns a Promise. Inside it, await pauses until a Promise settles and then unwraps the value, so the code reads top to bottom even though it is waiting.

// src/basic.ts
async function double(n: number): Promise<number> {
    return n * 2;
}

async function main(): Promise<void> {
    const a = await double(5);
    const b = await double(a);
    console.log(a);
    console.log(b);
}

main();

Output:

10
20

double is marked async, so although its body just returns n * 2, its actual return type is Promise<number>. Inside main, await double(5) suspends until that promise settles and unwraps 10 into a; await double(a) then unwraps 20 into b. The two logs print 10 and 20 in order. Without await, a would hold a Promise object rather than the number, and the arithmetic in the second call would break.


Technical Depth: The Claim, the Two Outcomes, then, and Collecting Together

Calling an async function hands back a claim, awaiting it can resolve or reject, .then is the same machinery in callback form, and Promise.all collects several claims in order.

The claim is not the value

Calling an async function returns a Promise immediately. The value inside it appears only after you await, so the claim and the value are different things.

// src/ticket.ts
async function resole(): Promise<string> {
    return "boots";
}

async function main(): Promise<void> {
    const claim = resole();          // a Promise, not the value
    console.log(claim instanceof Promise);
    const boots = await claim;       // present the ticket
    console.log(boots);
}

main();

Output:

true
boots

resole() returns at once with a Promise, so claim instanceof Promise is true: it is the ticket, not the boots. Only await claim unwraps the finished value "boots" into boots. Reading claim directly, expecting the string, would give the Promise object instead, which is the mistake of trying to wear the ticket.

Resolve or reject, caught with try and catch

A settled promise either resolves with a value or rejects with an error. Awaiting a rejection throws at the await, so a try/catch around it reads the apology.

// src/collect.ts
async function collect(ready: boolean): Promise<string> {
    if (!ready) {
        throw new Error("not ready");
    }
    return "resoled";
}

async function main(): Promise<void> {
    try {
        const ok = await collect(true);
        console.log(ok);
        const bad = await collect(false);
        console.log(bad);            // not reached
    } catch (err) {
        console.log("caught: " + (err as Error).message);
    }
}

main();

Output:

resoled
caught: not ready

collect(true) resolves with "resoled", which prints. collect(false) throws inside the async function, so its promise rejects, and await re-throws at the call site; control jumps to the catch, the console.log(bad) line is never reached, and the handler prints "caught: not ready". Awaiting a promise turns a rejection back into an ordinary thrown error you can catch with familiar syntax.

then and catch are the same machinery

Before async/await, the same promises were consumed with .then for the value and .catch for the error. The keywords are sugar over exactly this.

// src/then.ts
function step(): Promise<number> {
    return Promise.resolve(3);
}

step()
    .then((n) => n * 2)
    .then((n) => {
        console.log(n);
    });

Output:

6

step resolves with 3. The first .then receives 3, returns 3 * 2, which is 6, and that value flows into the next .then, which prints 6. Each .then returns a new promise carrying whatever its callback returned, which is how the chain threads a value along; await is simply a more linear way to write the same steps.

Collecting several claims together

Promise.all takes an array of promises and resolves once every one has, handing back the results in the same order as the input, regardless of the order they finished.

// src/together.ts
async function price(units: number): Promise<number> {
    return units * 10;
}

async function main(): Promise<void> {
    const results = await Promise.all([price(2), price(5), price(3)]);
    console.log(results.join(" "));
    const total = results.reduce((a, b) => a + b, 0);
    console.log(total);
}

main();

Output:

20 50 30
100

The three claims price 2, 5, and 3 units at ten each, giving 20, 50, and 30. Promise.all waits for all three and returns them in input order as [20, 50, 30], which joins to "20 50 30"; the order is fixed by the array position, not by which settled first. The reduce then sums them to 100. This is how you wait on several independent claims at once instead of one after another.

The async vocabulary

TermWhat it is
Promisea claim on a value that will be ready later
asyncmarks a function whose return is wrapped in a Promise
awaitsuspends until a Promise settles, then unwraps it
resolvethe Promise completes with a value
rejectthe Promise fails with an error

The five terms describe one mechanism: an async function hands back a Promise, which later resolves or rejects, and await is how a caller waits for and unwraps that outcome.


Real World Example: Pricing an Order's Lines Concurrently

An order arrives as a list of lines, each a stock code and a quantity. Pricing a line is modelled as an async lookup, so the depot fires all the lookups at once with Promise.all rather than waiting for each in turn, then builds a report whose total column sums the priced lines.

// src/orders.ts
const RATES: Record<string, number> = { widget: 40, gasket: 15, bolt: 5 };

async function lineTotal(sku: string, qty: number): Promise<number> {
    const rate = RATES[sku] ?? 0;
    return rate * qty;
}

function pad(text: string, width: number): string {
    return text.padEnd(width);
}

const LINES: { sku: string; qty: number }[] = [
    { sku: "widget", qty: 3 },
    { sku: "gasket", qty: 4 },
    { sku: "bolt", qty: 10 },
];

async function main(): Promise<void> {
    const totals = await Promise.all(LINES.map((l) => lineTotal(l.sku, l.qty)));
    const rows: string[] = [];
    let grand = 0;
    for (let i = 0; i < LINES.length; i++) {
        const t = totals[i];
        grand += t;
        rows.push(pad(LINES[i].sku, 8) + pad(String(LINES[i].qty), 6) + String(t));
    }
    const report = [
        "lines: " + LINES.length,
        pad("SKU", 8) + pad("QTY", 6) + "TOTAL",
        ...rows,
        "grand: " + grand,
    ];
    console.log(report.join("\n"));
}

main();

Output:

lines: 3
SKU     QTY   TOTAL
widget  3     120
gasket  4     60
bolt    10    50
grand: 230

Each line is priced by lineTotal, an async function returning a Promise<number>. LINES.map turns the three lines into three promises, and Promise.all waits for all of them and hands back the totals in the same order as the lines, so totals[i] always matches LINES[i]. That order guarantee is what lets the loop pair each total with its line without tracking which finished first.

Trace the totals against the rates. The widget line is 3 at 40, which is 120; the gasket line is 4 at 15, which is 60; the bolt line is 10 at 5, which is 50. The grand total accumulates 120 + 60 + 50, which is 230, printed in the footer. The report joins a count of 3 lines, the column header, the three padded rows, and the grand total.

The design has real limits worth naming. The sharpest flaw is that lineTotal is async in name only: it does no real waiting, just a multiplication wrapped in a Promise, so the Promise.all buys no concurrency at all and only adds the overhead of the promise machinery around a synchronous calculation. Marking a pure function async is a smell that misleads readers into thinking it does I/O. The second flaw is that RATES[sku] ?? 0 prices an unknown stock code at zero rather than failing, so a typo in a line silently becomes a free item that no error ever flags; a real pricer should reject an unknown code. And under noUncheckedIndexedAccess the totals[i] read would be number | undefined, a check the loose config here quietly skips. Concurrency helps only when the work genuinely waits; wrapping arithmetic in a promise just to use await adds ceremony without benefit.


Common Mistakes

  1. Using a Promise without awaiting it. Reading a field off the result of an async call, without await, reads the Promise object rather than the value, so the field is undefined and arithmetic on it is NaN. Await the claim to get the value.
  1. Forgetting that an async function always returns a Promise. Even a body that returns a plain number has the type Promise<number>, so a caller must await it or chain .then; treating the call as if it returned the raw value is a type error.
  1. Leaving a rejection unhandled. A promise that rejects with no await in a try/catch and no .catch becomes an unhandled rejection that can crash the process. Every claim that can reject needs somewhere to read the error.
  1. Awaiting independent work in sequence. Writing await a(); await b(); when a and b do not depend on each other runs them one after another. Start both and await Promise.all([a(), b()]) to overlap them.
  1. Expecting Promise.all to preserve completion order. Promise.all returns results in input order, not the order they settled, so do not assume the first to finish is first in the array; the array position is fixed by the input.
  1. Assuming Promise.all is partial. If any one promise rejects, Promise.all rejects immediately and the other results are lost. Use Promise.allSettled when you need every outcome regardless of failures.
  1. Marking a pure function async for no reason. Wrapping a synchronous calculation in async adds Promise overhead and misleads readers into thinking it waits on I/O. Reserve async for functions that genuinely await something.
  1. Mixing await into a forEach callback and expecting it to wait. forEach ignores the returned promises, so the loop does not pause. Use a for...of loop with await inside, or map to promises and await Promise.all.
  1. Silently defaulting a missing lookup instead of failing. Falling back to zero or an empty value on a missing key hides a real error, such as an unknown stock code, behind a plausible-looking result. Reject the bad input instead.

Best Practices

  • Await a claim before using its value. Treat the result of an async call as a ticket and unwrap it with await before reading fields or doing arithmetic, so you never operate on the Promise object by mistake.
  • Wrap awaited rejections in try and catch. Put a try/catch around an await that can reject, so the error has a place to be read instead of becoming an unhandled rejection.
  • Overlap independent work with Promise.all. When several async calls do not depend on each other, start them together and await them as a group rather than one after another, so their waiting overlaps.
  • Rely on Promise.all's input order. Pair each result with its input by array position, since Promise.all returns results in the order they were listed, not the order they finished.
  • Reach for allSettled when every outcome matters. Use Promise.allSettled instead of Promise.all when one failure should not discard the other results, and inspect each settled outcome.
  • Keep async only where there is real waiting. Do not mark a purely synchronous function async; reserve the keyword for functions that genuinely await I/O or a timer, so the type tells the truth.
  • Loop with for...of and await, not forEach. When each iteration must wait, use a for...of loop with await inside it, or map to promises and await them together, because forEach will not pause for a returned promise.
  • Fail on a missing lookup rather than defaulting. When a key must exist, reject or throw on its absence instead of silently substituting zero, so a typo surfaces as an error rather than a quietly wrong total.

Practice Exercises

  1. The claim and the value. Write an async function greet(name) that returns a greeting string, call it without await and log the result, then call it with await and log again, and explain why the two logs differ.
  1. The two outcomes. Write an async parseAmount(text) that resolves with a number when the text is numeric and throws otherwise, then call it inside a try/catch for both a good and a bad input and print each outcome.
  1. Overlapping the work. Given an async price(units), price three quantities both with three sequential awaits and with a single Promise.all, and confirm the results match while the second form overlaps the waiting.
  1. The lost failure. Show that Promise.all rejects entirely when one of its promises rejects, then switch to Promise.allSettled and print which entries succeeded and which failed.