#39 · Async

Find the bug · #39 · Async Medium JavaScript

The order count crashes

The profile page counts a user’s orders and crashes on “reading length”.

On this page

The report

Bug report

The profile page shows how many orders a user has placed. It crashes with “Cannot read properties of undefined (reading ’length’)”.

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
// How many orders a user has placed.
function orderCount(userId, api) {
  return api.getUser(userId)
    .then((user) => {
      api.getOrders(user.id);
    })
    .then((orders) => orders.length);
}

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 api = { getUser: async (id) => ({ id }), getOrders: async () => ['o1', 'o2', 'o3'] };
try {
  console.log(await orderCount(7, api));
} catch (e) {
  console.log(e.constructor.name + ': ' + e.message);
}

It prints

TypeError: Cannot read properties of undefined (reading 'length')

It should print

3
Show the answer: the bug, the fix, and how you’d find it

The bug (line 5)

The callback on lines 4–6 calls api.getOrders but doesn’t return its promise. Each then passes on whatever its callback returns, and this one returns undefined, so the next then gets undefined and line 7 reads .length of it. With braces around an arrow function’s body you need an explicit return.

The fix

2function orderCount(userId, api) {3  return api.getUser(userId)4    .then((user) => {5      api.getOrders(user.id);5      return api.getOrders(user.id);6    })7    .then((orders) => orders.length);8}

How you’d find it

  1. Reproduce: the error says it read length of undefined, on line 7.
  2. So orders is undefined. It comes from whatever the previous then returned.
  3. Read that callback: it has braces and no return. The orders promise is created and thrown away.

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.equal(await orderCount(7, { getUser: async (id) => ({ id }), getOrders: async () => [1, 2] }), 2);

Where else this bites

  • An arrow function with braces: x => { x * 2 } returns undefined; x => x * 2 doesn’t.
  • Middleware chains and reducers that forget to return.
Your progress stays on this device.