12.5. Run three tasks in sequence: chaining, then async/await
Topics
This question is in
12. Callbacks, promises and asyncAn order page loads in three steps that depend on each other: find the user, then that user's orders, then the total of those orders. Each step returns a promise, and each needs the result of the one before it. Writing that sequence well is the core skill of promise code, and it can be written two ways: as a chain of .then calls, or as an async function with await. Writing both shows what await really does.
In load.js, write loadWithThen(api, id) with a .then chain and loadWithAwait(api, id) with async/await. Both do the same work.
Signature
function loadWithThen(api, id) // returns a Promise
async function loadWithAwait(api, id) // returns a Promiseapi has three methods, each returning a promise:
api.getUser(id)fulfills with a user object.api.getOrders(user)fulfills with an array of that user's orders.api.getTotal(orders)fulfills with a number.
Both functions fulfill with { user, orders, total }.
Requirements
- Each function returns a promise that fulfills with an object holding the user, the orders and the total.
- The steps run in order,
getUser, thengetOrders, thengetTotal, each called with the previous step's result. - Each step starts only after the previous one has fulfilled, and right away when it does.
- The returned promise settles only after the last step.
- If a step rejects, the returned promise rejects with that same error, and no later step is called.
loadWithThenuses.thenand contains noasyncorawait.loadWithAwaitis anasyncfunction that usesawaitand no.then.
Examples
const api = {
getUser: (id) => Promise.resolve({ id, name: "Ada" }),
getOrders: (user) => Promise.resolve([{ price: 30 }, { price: 12 }]),
getTotal: (orders) => Promise.resolve(orders.reduce((sum, order) => sum + order.price, 0)),
};
await loadWithThen(api, "u1");
// { user: { id: "u1", name: "Ada" }, orders: [{ price: 30 }, { price: 12 }], total: 42 }await loadWithAwait(api, "u1"); // the same objectconst broken = { ...api, getOrders: () => Promise.reject(new Error("orders are down")) };
await loadWithAwait(broken, "u1"); // rejects with "orders are down"; getTotal is never calledEnvironment
- Plain JavaScript in a browser page; the tests call the globals
loadWithThenandloadWithAwaitfromload.js. - The tests' api answers on a virtual clock (
setTimeout), so no test waits for real time. - The api methods always return promises; a method that throws instead is out of scope.
- Do not catch the errors: the caller handles them.
Hints
- A value returned from a
.thenhandler becomes the next promise's value. How does the last handler still see the user from the first step? - What does
awaitdo when the promise it waits for rejects?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it