Question 14
Back to Exercise
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
const loadData = () => Promise.reject(new Error("network error"));
async function safeLoad() {
try {
return loadData();
} catch {
return "cached data";
}
}
safeLoad().then((v) => console.log("got", v)).catch((e) => console.log("escaped:", e.message));
- A catch without a parameter is invalid
- B return loadData() returns the promise without awaiting it, so the rejection happens outside try – write return await loadData() Correct
- C loadData must be async
- D try/catch never works in async functions
Correct Answer: Option B
With return await the rejection throws inside try, the catch returns "cached data", and the caller prints got cached data.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!