Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Promise catch() Method

JavaScript Promise catch() Method

JavaScript Promise catch() method is called whenever a promise is rejected. This method itself returns a promise so it can also be used to chain promises. This method is used for error handling. This method is mainly used after .then to chain a promise and handle reject condition. This method internally calls .then with undefined and rejected conditions as arguments. 

Syntax:

catch(()=>{})

Parameter: This method takes a callback function that decides what action to perform when the promise is rejected

Return Type: This method returns a promise which is in the pending state even if the previous promise is finished.

Example 1: This example uses the catch method to handle the reject condition of a promise.

Javascript




let prom1 = new Promise((resolve, reject) => {
    reject("Failure");
})
    .then(e => { console.log("Hello Successful") })
    .catch((e) => { console.log(e) })


Output: Since the promise returns a reject it moves to the catch method where the rejected value is received and printed on the console.

Failure

Example 2: This example specifies a condition where the catch method fails to catch an error.

Javascript




let prom1 = new Promise((resolve, reject) => {
    setTimeout(() => { throw new Error("Failure") }, 1000);
})
 
prom1.catch((e) => { console.log(e) })


Output: Normally this error should be caught by the catch block but since the error is thrown by an asynchronous function the catch block fails to handle it.

 

Example 3: This method explains the condition when the catch method will not be called.

Javascript




let x = 10;
let y = 10;
let prom1 = new Promise((resolve, reject) => {
    if (x == y) {
        resolve("Equal Values")
    } else {
        reject("Unequal Values")
    }
})
 
prom1.then((e) => { console.log(e) });
prom1.catch((e) => { console.log(e) })


Output: The catch method is not called as the promise is resolved so only then the method is called.

Equal Values

Supported Browsers: 

  • Google Chrome
  • Mozilla Firefox 
  • Opera 
  • Safari 
  • Edge 

We have a complete list of Javascript Promise methods, to check those please go through the Javascript Promise Reference article.

RELATED ARTICLES

Most Popular

Recent Comments