Find the bug · #37 · Async Easy JavaScript
Every account looks deactivated
Since the user service went async, every account page shows a “Deactivated” banner.
On this page
The report
After the user service moved to an async database, every account page shows a red “Deactivated” banner, even for active users.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Shows a "Deactivated" banner for inactive accounts.
async function bannerFor(id, db) {
const user = db.getUser(id);
return user.active ? 'none' : 'Deactivated';
}Read it, then pick a line.
What does db.getUser return now: the user, or something else?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const db = { getUser: async (id) => ({ id, active: true }) };
console.log(await bannerFor(1, db));It prints
Deactivated
It should print
none
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 calls db.getUser, which is async and returns a Promise, without await. A promise has no active property, so user.active is undefined, which is falsy, and every user looks deactivated. Await the promise.
The fix
1// Shows a "Deactivated" banner for inactive accounts.2async function bannerFor(id, db) {3 const user = db.getUser(id);3 const user = await db.getUser(id);4 return user.active ? 'none' : 'Deactivated';5}How you’d find it
- Reproduce with an active user: the banner still says “Deactivated”.
- Log
useron line 4:Promise { … }, not a user. Souser.activeisundefined. - The report says it started when the database went async: that’s exactly when
getUserbegan returning a promise.
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.
const db = { getUser: async (id) => ({ id, active: id !== 2 }) };
assert.equal(await bannerFor(1, db), 'none');
assert.equal(await bannerFor(2, db), 'Deactivated');Where else this bites
if (await isAllowed())written asif (isAllowed()): a promise is always truthy.- Python has the same trap with coroutines (see “Out-of-stock items still go in the cart”).