Bird
Raised Fist0
Node.jsframework~10 mins

Promise catch for async errors in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Promise catch for async errors
Start async operation
Promise created
Async operation succeeds?
NoError thrown
Catch error
Resolve promise
Handle error
Then block runs
End
This flow shows how a Promise runs an async task, then either resolves successfully or catches errors to handle them.
Execution Sample
Node.js
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject('Network error'), 1000);
  });
}

fetchData()
  .then(data => console.log('Data:', data))
  .catch(err => console.log('Error:', err));
This code creates a Promise that fails after 1 second, then catches and logs the error.
Execution Table
StepActionPromise StateOutput
1fetchData() called, Promise createdPending
2setTimeout triggers after 1s, reject calledRejected
3Promise catch runs due to rejectionRejectedError: Network error
4No then block runs because Promise rejectedRejected
5Execution ends after catch handles errorRejectedError logged
💡 Promise rejected, catch block handled the error, stopping further then execution.
Variable Tracker
VariableStartAfter 1sFinal
Promise StatePendingRejectedRejected
OutputError: Network error
Key Moments - 2 Insights
Why doesn't the then block run when the Promise is rejected?
Because the Promise state changes to rejected (see step 2 and 3 in execution_table), only the catch block runs to handle the error.
What happens if we don't add a catch block?
Without catch, the rejected Promise causes an unhandled rejection error, which can crash the program or show warnings (not shown in this trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the Promise state at step 2?
ARejected
BResolved
CPending
DSettled
💡 Hint
Check the 'Promise State' column at step 2 in execution_table.
At which step does the catch block run?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look for 'Promise catch runs' in the Action column of execution_table.
If the Promise resolved successfully instead of rejecting, what would change in the execution_table?
AStep 2 would show Rejected state
BStep 3 would show then block running instead of catch
CStep 5 would show error logged
DNo change, catch still runs
💡 Hint
Refer to the Promise State and Output columns in execution_table for success vs error.
Concept Snapshot
Promise catch for async errors:
- Create a Promise for async work
- If error occurs, reject the Promise
- Use .catch() to handle errors
- .then() runs only if Promise resolves
- Catch prevents unhandled rejections
- Always add catch for safe async code
Full Transcript
This visual trace shows how a Promise handles asynchronous errors using catch. First, the Promise is created and starts pending. After 1 second, the Promise rejects with an error. Because of rejection, the catch block runs to handle the error, logging it. The then block does not run because the Promise did not resolve successfully. This pattern helps safely manage errors in async code by catching them and preventing crashes or warnings. Always add a catch block after then to handle possible errors.

Practice

(1/5)
1. What is the main purpose of using catch with a Promise in Node.js?
easy
A. To log the successful result of the Promise
B. To start the asynchronous operation
C. To handle errors that occur during the asynchronous operation
D. To convert a Promise into a synchronous function

Solution

  1. Step 1: Understand what catch does in Promises

    The catch method is designed to handle any errors that happen during the execution of a Promise or in the chain of Promises.
  2. Step 2: Identify the role of catch in error handling

    It catches rejected Promises or exceptions thrown inside then callbacks, preventing unhandled errors.
  3. Final Answer:

    To handle errors that occur during the asynchronous operation -> Option C
  4. Quick Check:

    Promise catch = error handler [OK]
Hint: Remember: catch always handles errors in promises [OK]
Common Mistakes:
  • Thinking catch starts the async operation
  • Confusing catch with success handlers
  • Believing catch makes code synchronous
2. Which of the following is the correct syntax to catch errors from a Promise named myPromise?
easy
A. myPromise.error(error => console.log(error));
B. myPromise.catch(error => console.log(error));
C. myPromise.then(error => console.log(error));
D. myPromise.finally(error => console.log(error));

Solution

  1. Step 1: Recall the Promise error handling syntax

    The correct method to handle errors in a Promise is catch, which takes a callback for the error.
  2. Step 2: Match the syntax with the options

    myPromise.catch(error => console.log(error)); uses catch correctly with an arrow function to log the error.
  3. Final Answer:

    myPromise.catch(error => console.log(error)); -> Option B
  4. Quick Check:

    Use catch for errors in Promises [OK]
Hint: Use .catch() after Promise to handle errors [OK]
Common Mistakes:
  • Using then to catch errors
  • Using non-existent error method
  • Confusing finally with error handling
3. What will be logged to the console when running this code?
Promise.reject('Error happened')
  .catch(err => console.log('Caught:', err));
medium
A. Caught: Error happened
B. Error happened
C. Uncaught Error happened
D. Nothing is logged

Solution

  1. Step 1: Understand Promise.reject and catch

    Promise.reject('Error happened') creates a rejected Promise with the error message 'Error happened'.
  2. Step 2: Analyze the catch callback

    The catch method receives the error and logs it prefixed with 'Caught:'.
  3. Final Answer:

    Caught: Error happened -> Option A
  4. Quick Check:

    Rejected Promise caught logs error [OK]
Hint: Rejected Promise triggers catch callback [OK]
Common Mistakes:
  • Expecting error to be logged without 'Caught:' prefix
  • Thinking error is uncaught and crashes program
  • Assuming nothing logs because of rejection
4. Identify the error in this code snippet that tries to catch a Promise rejection:
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(console.error());
medium
A. The response.json() call should be inside catch
B. The then methods are missing error handlers
C. The fetch function does not return a Promise
D. The catch method is called with the result of console.error() instead of a function

Solution

  1. Step 1: Check how catch is used

    The code calls console.error() immediately and passes its result (undefined) to catch, which expects a function.
  2. Step 2: Understand correct catch usage

    catch should receive a function reference or arrow function, like catch(error => console.error(error)).
  3. Final Answer:

    The catch method is called with the result of console.error() instead of a function -> Option D
  4. Quick Check:

    Pass function to catch, not call it [OK]
Hint: Pass function to catch, don't call it immediately [OK]
Common Mistakes:
  • Calling console.error() inside catch instead of passing function
  • Ignoring that fetch returns a Promise
  • Misplacing response.json() call
5. 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));
hard
A. Error caught: Failed to load\nResult: Default data
B. Data: Failed to load\nResult: undefined
C. Uncaught Failed to load error, program crashes
D. Only Error caught: Failed to load is logged

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]
Hint: 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