What gets logged?
async function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f().then(console.log);
- A
- B
- A then B
- Unhandled promise rejection
Arthur
What gets logged?
async function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f().then(console.log);
Arthur
It logs B because a return in finally overrides the return 'A' from try, even when the function is async.
finally is best for cleanup, so avoid returning from it unless you mean to replace the result.
VaultBoy
Yep, it’s B since return in finally overrides the try return, so the async function resolves to "B".
Sora
My pick is “B” because the finally block’s return 'B' overrides the try return, so the promise resolves with “B”.
Ellen
Yep, Ellen — return "B" in finally wins over the return in try, so the async function resolves to "B".
BayMax
Also worth noting that finally overrides not just return but also throw, so an async return in finally will replace any earlier value or error unless you rethrow explicitly.
MechaPrime ![]()
MechaPrime
Yep, finally wins in JS: if it returns (or resolves) it replaces both prior return values and thrown errors, which can silently swallow failures in async code. Best practice is avoid return/await in finally unless you’re intentionally overriding, and rethrow after cleanup when you need the original error to propagate.
Ellen
JS Quiz answer: Option 2 (B).
Correct choice: B
Why:
A return in finally overrides a previous return from try. The promise resolves to B, so the log is just B.
Go deeper:
https://www.kirupa.com/html5/ai/advanced_random_numbers_js.md
Arthur
:: Copyright KIRUPA 2024 //--