Promise: .then() method & catch() method - 02

.then() method:

After resolving the Promise if we want to add more logic, then we can do this by the .then() method. It’s a higher-order function. It can take 2 callback functions as arguments also known as a handler. 

The first callback function is also known as onFulfilled or success handler. The second callback function is also known as onRejected or failure handler. We can invoke .then() with one, both, or neither handler!

One important feature of .then() is that it always returns a promise.



onFulfilled: 

When we use the success handler or onFulfilled function in the .then() method, the success handler function will link with Promise. Then the Promise’s resolve value will pass through the success handler.


const prom = new Promise((resolve, reject) => {
      resolve("Yay!");
    });

const handleSuccess = (resolvedValue) => {
      console.log(resolvedValue);
};

prom.then(handleSuccess); // Prints: 'Yay!'

onRejected: 

When we use the failure handler or onRejected function in the .then() method, the failure handler function will link with Promise. Then the Promise’s rejected value will pass through the failure handler.


  let prom = new Promise((resolve, reject) => {
      let num = Math.random();

      if (num < 0.5) {
        resolve("Yay!");
      } else {
        reject("Ohhh noooo!");
      }
    });

    const handleSuccess = (resolvedValue) => {
      console.log(resolvedValue);
    };

    const handleFailure = (rejectionReason) => {
      console.log(rejectionReason);
    };

    prom.then(handleSuccess, handleFailure);


Using catch() with Promises

We can write the callback functions of .then  separately. Here onRejected or failure handler will include on the next .then.



prom
      .then((resolvedValue) => {
        console.log(resolvedValue);
})

    .then(null, (rejectionReason) => {
    console.log(rejectionReason);
 });


To write cleaner code, we can use the .catch() function(takes only one argument) for failure handlers.


prom
      .then((resolvedValue) => {
        console.log(resolvedValue);
   })

     .catch((rejectionReason) => {
      console.log(rejectionReason);
});

Post a Comment

Previous Post Next Post