Find the bug · #38 · Async Easy JavaScript
The cart total is ₹0
The cart page shows a total of ₹0 every time, even with items in the cart.
On this page
The report
Prices now come from a separate pricing service. Since then, the cart page shows a total of ₹0 every time it loads, even with items in the cart.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Adds up the cart, asking the pricing service for each item's price.
async function cartTotal(ids, getPrice) {
let total = 0;
ids.forEach(async (id) => {
total += await getPrice(id);
});
return total;
}Read it, then pick a line.
Does forEach wait for the promises its callback returns?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const getPrice = async (id) => ({ a: 100, b: 250 })[id];
console.log(await cartTotal(['a', 'b'], getPrice));It prints
0
It should print
350
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 uses forEach with an async callback. forEach doesn’t wait for the promises its callbacks return: it starts them all and finishes at once, so line 7 returns total while it’s still 0. The additions happen later, when nobody is looking. Use for...of with await (or Promise.all).
The fix
1// Adds up the cart, asking the pricing service for each item's price.2async function cartTotal(ids, getPrice) {3 let total = 0;4 ids.forEach(async (id) => {4 for (const id of ids) {5 total += await getPrice(id);6 });6 }7 return total;8}How you’d find it
- Reproduce: two items, and the total is 0.
- Add a log after the loop and one inside the callback: the “after” log prints first. The function returns before any price arrives.
forEachwas written before promises existed and ignores the callback’s return value, promise or not.
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 cartTotal(['a', 'b', 'a'], async (id) => ({ a: 1, b: 2 })[id]), 4);Where else this bites
array.map(async ...)withoutPromise.allgives you an array of promises.- Saving each item in a list with
forEach(async ...)and then saying “all saved”.