Find the bug · #42 · Async Hard JavaScript
Failed saves are never retried
Drafts that fail to save should go to a retry queue, but the queue is always empty.
On this page
The report
When saving a draft fails (on a bad network, say), the draft should go into a retry queue. In production the queue is always empty, and users lose drafts whenever the network blips.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Saves a draft; if saving fails, the draft is queued to retry later.
async function saveDraft(draft, api, retryQueue) {
try {
return api.save(draft);
} catch (err) {
retryQueue.push(draft);
return 'queued';
}
}Read it, then pick a line.
When does the try block finish: when the save succeeds or fails, or as soon as line 4 hands back a promise?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const api = { save: async () => { throw new Error('network down'); } };
const queue = [];
try {
console.log(await saveDraft({ id: 1 }, api, queue));
} catch (e) {
console.log('error: ' + e.message);
}
console.log('queued drafts: ' + queue.length);It prints
error: network down queued drafts: 0
It should print
queued queued drafts: 1
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 returns the promise from api.save without awaiting it. The try block is done the moment the promise is handed back, so when it rejects a little later, the catch is long gone and the error goes straight to the caller. return await keeps the rejection inside the try.
The fix
1// Saves a draft; if saving fails, the draft is queued to retry later.2async function saveDraft(draft, api, retryQueue) {3 try {4 return api.save(draft);4 return await api.save(draft);5 } catch (err) {6 retryQueue.push(draft);7 return 'queued';How you’d find it
- Reproduce with a save that always fails: the caller gets the error, and the queue stays empty.
- So the
catchnever ran, even though the error came from inside thetry. Put a log in the catch to be sure: silent. - The
tryonly catches errors thrown while it’s running. A promise that rejects after being returned is outside it.
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 queue = [];
const result = await saveDraft({ id: 2 }, { save: async () => { throw new Error('x'); } }, queue);
assert.equal(result, 'queued');
assert.equal(queue.length, 1);
assert.equal(await saveDraft({ id: 3 }, { save: async () => 'saved' }, []), 'saved');Where else this bites
try { promise.then(...) }catching nothing for the same reason.- Python: returning a coroutine from inside
trywithout awaiting it.