All sample questions / JavaScript
What does console.log(trace.join(' ')) print? JavaScript Promises, async await and the Event Loop
Block 6, Promises, async await and the Event Loop, question 13 of the JavaScript sample
const trace = [];
async function main() {
try {
await Promise.all([Promise.resolve(1), Promise.reject(new Error('mid-fail')), Promise.resolve(3)]);
trace.push('never');
} catch (e) {
trace.push('caught:' + e.message);
}
console.log(trace.join(' '));
}
main();
What does this print?
Show the answer and why each option is right or wrong
Answer, B. caught:mid-fail
- A. caught:undefined
- Assumes the error thrown by the await loses its message once it reaches the catch block. The catch block receives the original Error object with its message intact.
- B. caught:mid-fail
- Correct. Awaiting a Promise.all that rejects throws inside the try block, and the catch receives that exact rejection.
- C. never
- Assumes awaiting a Promise.all that contains a rejection still resolves normally, letting execution continue past it. A rejection anywhere in the array makes the whole Promise.all reject, which await then turns into a thrown exception.
- D. caught:1,mid-fail,3
- Assumes the catch handler somehow receives every value from the array combined into one string. Promise.all rejects with the single reason from the promise that actually rejected, not with the other resolved values.
A rejected Promise.all behaves like any other rejected promise when awaited, it throws at the await expression with the same reason the combined promise rejected with. A surrounding try catch handles that throw exactly as it would a rejection from a single promise, and the other successfully resolved entries are simply not part of the rejection reason.
The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 JavaScript questions, 9 euros
Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.