Question 22
Question
What is the difference between .then()
and .catch()
in promise chains?
Answer
.then()
and .catch()
are methods used in promise chains to handle different outcomes of a Promise. They let you define what happens when a Promise successfully resolves or rejects:
1. .then(onFulfilled):
Purpose: Executed when the Promise is fulfilled (resolves successfully).
Parameter
onFulfilled
: A function that receives the result of the fulfilled Promise as its argument. This function will be called with the resolved value if everything goes as expected.Example:
2. .catch(onRejected):
Purpose: Executed when the Promise is rejected (an error occurs).
Parameter
onRejected
: A function that receives the reason for the rejection as its argument. This function will be called if something goes wrong during the asynchronous operation.Example:
Key Points:
You can chain multiple
.then()
calls to perform sequential actions after a successful resolution.The
catch
block is crucial for graceful error handling in asynchronous code.
Last updated