LearnFrenzy
Sign in Take a free test

Async/Await · Find the Error · Question 14

Bug: the fallback is never used Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links