The catch(onRejected) method

The catch() method of a Promise object is used instead of the then() method when we use the then() method only to handle errors and exceptions. There is nothing special about how the catch() method works. It's just that it makes the code much easier to read, as the word catch makes it more meaningful.

The catch() method just takes one argument, that is, the onRejected callback. The onRejected callback of the catch() method is invoked in the same way as the onRejected callback of the then() method.
The catch() method always returns a promise. Here is how a new Promise object is returned by the catch() method:

  • If there is no return statement in the onRejected callback, then a new fulfilled Promise is created internally and returned.
  • If we return a custom Promise, then it internally creates and returns a new Promise object. The new promise object resolves the custom promise object.
  • If we return something else other than a custom Promise in the onRejected callback, then a new Promise object is created internally and returned. The new Promise object resolves the returned value.
  • If we pass null instead of the onRejected callback or omit it, then a callback is created internally and used instead. The internally created onRejected callback returns a rejected Promise object. The reason for the rejection of the new Promise object is the same as the reason for the rejection of a parent Promise object.
  • If the Promise object to which catch() is called gets fulfilled, then the catch() method simply returns a new fulfilled promise object and ignores the onRejected callback. The fulfillment value of the new Promise object is the same as the fulfillment value of the parent Promise.

To understand the catch() method, consider this code:

ajaxPromiseCall('http://invalidURL.com')
.then(success => { console.log(success) },
failed => { console.log(failed) });

This code can be rewritten in this way using the catch() method:

ajaxPromiseCall('http://invalidURL.com')
.then(success => console.log(success))
.catch(failed => console.log(failed));

These two code snippets work more or less in the same way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.200.246