Run promises in parallel and handle failures

“Kitchen rush”, a Black belt challenge from the CurlyScript Dojo. It uses what Freshman Year: Asynchronous JavaScript: Waiting Without Freezing teaches, and 3 tests check your answer.

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.

Example
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.

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; })() gives true

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
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.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning