Bird
0
0

Given this code, what will be the output and why?

hard📝 state output Q15 of 15
Node.js - Error Handling Patterns
Given this code, what will be the output and why?
async function getData() {
  return Promise.reject('Failed to load');
}

getData()
  .then(data => console.log('Data:', data))
  .catch(err => {
    console.log('Error caught:', err);
    return 'Default data';
  })
  .then(result => console.log('Result:', result));
AError caught: Failed to load\nResult: Default data
BData: Failed to load\nResult: undefined
CUncaught Failed to load error, program crashes
DOnly Error caught: Failed to load is logged
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the rejected Promise from getData

    The function returns a rejected Promise with message 'Failed to load', so the first then is skipped and control goes to catch.
  2. Step 2: Understand the catch and subsequent then

    The catch logs the error and returns 'Default data', which resolves the Promise chain. The next then receives this value and logs it.
  3. Final Answer:

    Error caught: Failed to load Result: Default data -> Option A
  4. Quick Check:

    catch handles error and returns value for next then [OK]
Quick Trick: Returned value from catch goes to next then [OK]
Common Mistakes:
  • Thinking error stops the chain completely
  • Expecting no output after catch
  • Confusing rejected Promise with resolved data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes