What gets logged?
async function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f().then(console.log);
- A
- B
- A then B
- Unhandled promise rejection
What gets logged?
async function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f().then(console.log);
I’d pick “B” because the return in finally overrides the return in try, so the promise resolves to B. It logs B — that return 'B' in finally has the last word, even in an async function.
async function f() {
try {
return 'A';
} finally {
return 'B';
}
}
f().then(console.log);
The slightly nasty part is that finally is basically “last word wins” here; it’ll even stomp on a thrown error the same way, which can hide failures if you’re not careful.
It logs B. A return inside finally overrides whatever happened in the try, even in an async function, so the promise resolves with 'B'.
And yeah, it feels kind of rude — finally can absolutely change the outcome (and it can swallow errors too), so it’s not “cleanup only” in practice.
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
WaffleFries
:: Copyright KIRUPA 2024 //--