JavaScript, inside out · Chapter 40 of 51
Async and await
By the end of this chapter you can write async code that reads top to bottom, catch its failures with try, and choose between waiting one at a time and waiting for everything at once. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Going async
- 6 tasks
- JavaScript
- In the all labs plan
The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.
Why you need this
The promise chains work, but Anjali cannot follow them: "Which then is this, and where does the bill come from?" Then Meera opens the new dashboard during the 4 pm rush and waits three seconds for it. Kabir finds why: it fetches the orders, then the riders, then the stock, one after another, though none of them needs the others. And when Ravi messages every rider about the rain, one phone that is off must not stop the others hearing.
With chains, every step is a new callback, a value you need two steps later must be passed along by hand, and a try cannot catch anything, because the failure happens after the try has finished.
What you build: 6 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
getEta: when the rider will arrive
Write the async function getEta(api, orderId). api.getOrder(orderId) resolves to an order { id, item, riderId }, and api.getRider(riderId) resolves to a rider { name, eta } (eta in minutes). Look up the order, then its rider, and resolve to the rider's name, arrives in, the eta and min: 'Kiran arrives in 8 min'.
If a lookup rejects, getEta rejects with the same error.
- Task 2
safePay: a failed payment becomes a result
Write the async function safePay(gateway, amount). gateway.pay(amount) returns a promise. When it resolves, resolve to { ok: true, txn } with what it resolved to. When it rejects, even some time later, resolve to { ok: false, error } with the error's message, such as 'Bank server down'.
safePay itself never rejects.
- Task 3
prepareInOrder: kitchen steps strictly one after another
Write the async function prepareInOrder(steps). steps is an array of functions, each returning a promise. Call them one at a time: a step is only called after the previous step's promise has resolved. Resolve to an array of their results, in order.
If a step rejects, stop there: the steps after it are never called, and prepareInOrder rejects with that error. An empty array gives [].
- Task 4 · interview question
Interview: loadDashboard, three parts at the same time
loadDashboard(api) works now but is slow: it fetches the orders, then the riders, then the stock, one after another. Make it start api.getOrders(), api.getRiders() and api.getStock() at the same time, and resolve to { orders, riders, stock } once all three are in: when each takes 1 second, the dashboard is ready after 1 second, not 3.
If any of the three rejects, loadDashboard rejects with that error.
- Task 5
notifyRiders: who got the message and who did not
Write the async function notifyRiders(riders, message, send). Call send(rider, message) for every rider at once, without waiting between them; each call returns a promise. Wait until every one has either resolved or rejected, even when some fail, and resolve to { sent, failed }: the names of the riders whose promise resolved and of those whose promise rejected, each list in the riders' original order, whatever order the replies come in.
For Kiran, Salma, Arjun and Divya, where Salma and Arjun fail, it gives { sent: ['Kiran', 'Divya'], failed: ['Salma', 'Arjun'] }.
- Task 6
totalCups: count the cups in a live stream
Write the async function totalCups(stream). stream is any async iterable of orders { item, cups }, such as an async generator: not an array, so its values arrive one at a time as promises. Add up the cups of every order and resolve to the total.
An empty stream gives 0.
What you will learn
- async and await: pause a function until a promise settles, and write the next line as if the value were already there.
- try and catch with await: a rejection becomes an ordinary error.
- One at a time or all at once: a loop with await, Promise.all and Promise.allSettled.
- for await: walk values that arrive one by one.
More in Going async
Build "Async and await" yourself
Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.