Missing await: three checks before accepting the fix
This is an intentionally small JavaScript exercise for someone beginning to use asynchronous functions.
async function loadName(fetchUser) {
const user = fetchUser();
return user.name;
}
Before changing anything, predict two outcomes: what value does this resolve to if fetchUser succeeds, and what should happen if it rejects?
If fetchUser is async and resolves to { name: "Ana" }, the function above resolves to undefined: it reads a property from the Promise, before receiving the user object.
Wait where the value is needed
The fix waits at the first place where the result is needed:
const user = await fetchUser();
return user.name;
Check behavior without a real API
Here is a complete Node.js example, with the dependency injected so the checks do not need a network call. Save it as await-review.cjs and run node await-review.cjs.
const assert = require('node:assert/strict');
async function brokenLoadName(fetchUser) {
const user = fetchUser();
return user.name;
}
async function loadName(fetchUser) {
const user = await fetchUser();
return user.name;
}
async function main() {
const succeeds = async () => ({ name: 'Ana' });
assert.equal(await brokenLoadName(succeeds), undefined);
assert.equal(await loadName(succeeds), 'Ana');
await assert.rejects(
() => loadName(async () => { throw new Error('unavailable'); }),
/unavailable/
);
console.log('3 behavior checks passed: original result, corrected result, rejection propagation.');
}
main().catch(error => { console.error(error); process.exitCode = 1; });
What these checks establish
The checks establish the broken result, the corrected result and rejection propagation for these inputs. They are not proof of universal correctness. Await suspends this continuation rather than blocking the whole thread, and the caller still needs to decide how to handle rejection.
A useful review asks three questions: what value was returned before the change, where is the resolved value first needed, and what happens when the dependency fails?
Reference: MDN await.
Continue with an open exercise
I build DoesItHold, a debugging practice product. If you want a worked guide and a practice entry, this guide is free to read without an account.
Prepared with AI assistance; the three checks were executed locally. What other failure would you check before accepting this correction?
Comments
Join the discussionNo comments yet. Be the first to comment.