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:

    const promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("Success!"), 1000); // Simulate an asynchronous operation
    });
    
    promise
        .then((result) => {
            console.log(result); // Output: "Success!" after 1 second
        });

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:

    const promise = new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error("Something went wrong!")), 1000);
    });
    
    promise
        .catch((error) => {
            console.error(error); // Output: Error message after 1 second
        });

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