#41 · Async

Find the bug · #41 · Async Hard JavaScript

Prices come back empty

Fetching prices in parallel made the page faster, and every price empty.

On this page

The report

Bug report

To speed up the catalogue page, prices are now fetched in parallel. The page does load faster, but every price shows as empty.

The code

Read it first: what should it do? Then click the line where you think the bug is.

JavaScriptClick the line you think is wrong
// Fetches the price of every item in parallel.
async function fetchPrices(ids, getPrice) {
  return Promise.all(ids.map(async (id) => {
    await getPrice(id);
  }));
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
const getPrice = async (id) => ({ a: 100, b: 250 })[id];
console.log(JSON.stringify(await fetchPrices(['a', 'b'], getPrice)));

It prints

[null,null]

It should print

[100,250]
Show the answer: the bug, the fix, and how you’d find it

The bug (line 4)

The async callback on lines 3–5 awaits each price but never returns it, so every promise in the array resolves to undefined, and Promise.all faithfully gives back a list of undefineds. Return the value (or map straight to getPrice(id)).

The fix

1// Fetches the price of every item in parallel.2async function fetchPrices(ids, getPrice) {3  return Promise.all(ids.map(async (id) => {4    await getPrice(id);4    return await getPrice(id);5  }));6}

How you’d find it

  1. Reproduce: two ids, and the result is [undefined, undefined] (JSON prints them as null).
  2. The prices were fetched (log inside getPrice and you’ll see the calls), so they’re lost on the way back.
  3. Promise.all returns what each promise resolves to, and each callback resolves to its return value, which is nothing.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert.deepEqual(await fetchPrices(['b', 'a'], async (id) => ({ a: 1, b: 2 })[id]), [2, 1]);

Where else this bites

  • The same missing return as “The order count crashes”, one level deeper.
  • Python’s asyncio.gather over coroutines that don’t return.
Your progress stays on this device.