The challenge
Write an async function cookAll(dishes). For each dish name, call the provided cook(name), all at the same time. Return an array of results in the same order. If a dish fails, put "failed: NAME" in its place instead of crashing.
await cookAll(["rice", "pizza"])
// ["rice ✅", "failed: pizza"]
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
cookAll(["rice", "stew"])gives["rice ✅", "stew ✅"]cookAll(["rice", "pizza", "tacos"])gives["rice ✅", "failed: pizza", "tacos ✅"]- Dishes cook at the same time:
(async () => { const t = Date.now(); await cookAll(["a", "b", "c", "d"]); return Date.now() - t < 150; })()givestrue
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Promise.all(dishes.map(…)) runs them in parallel.
Hint 2
Catch each failure individually: cook(name).catch(() => failed: ${name}).
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
const cook = (name) => new Promise((resolve, reject) => {
setTimeout(() => (name === "pizza" ? reject(new Error("no oven")) : resolve(`${name} ✅`)), 50);
});
async function cookAll(dishes) {
return Promise.all(dishes.map((name) => cook(name).catch(() => `failed: ${name}`)));
}
Learn what you need
This exercise uses what Freshman Year: Asynchronous JavaScript: Waiting Without Freezing teaches. Read those notes first if any of it is new.