This write-up will discuss JavaScript Promise Error Handling with the help of suitable examples. So, let’s start!
JavaScript Promise Error Handling
Promises are used for managing the execution flow in a program. Chaining Promises is also useful when executing a series of asynchronous functions, where each depends on the prior function. In a Promise, you can utilize two methods for handling errors which are the “then()” method and the “catch()” block.
JavaScript Promise Error Handling using then() method
The “then()” method is executed when a promise is fulfilled or rejected. If the added Promise is fulfilled successfully, its related handler function will run. However, the error handler for the “then()” method will be executed in case of promise rejection.
Example: JavaScript Promise Error Handling using then() method
In the below-given example, we have added “then()” method, which comprises two callbacks, one is the success handler function and the other one is for error handling:
setTimeout(() => {
reject("An error is encountered");
}, 2000)});
promiseObj.then((response) => {
console.log(response);}, (error) => {
console.log(error); });
Execution of the above-given program will show you the following output:
As you can see from the output, that specified handler of the “then()” method is working perfectly; however, it also has some drawbacks. For instance, we may encounter any error in the success handler, but the added success handler cannot handle it. Also, in the case of using the then() method, you have to write an error handler for each “then()” block. In such situation, you can utilize “catch()” to overcome the mentioned drawbacks.
Example 1: JavaScript Promise Error Handling using catch() block
Now, we will add a catch() for handling the error or the rejection state of the promise:
setTimeout(() => {
reject("An error is encountered");
}, 2000)});
promiseObj.then((response) => {
console.log(response);}).catch((error) => {
console.log(error); });
When one of the added Promises gets rejected, the remaining promise chain will be terminated. That’s the reason only one console log is executed:
Example 2: JavaScript Promise Error Handling using catch() block
In the following example, first of all, attendance promise object will accept “Taylor” as name argument and then display it to the console. After that, the function will check if the promise function is fulfilled or rejected and execute the added code accordingly:
return new Promise((resolve, reject) => {
if (name === "Louis") {
return reject("Louis is present");
} else {
setTimeout(() => {
return resolve(name);
}, 2000);
}
});}
attendance("Taylor")
.then((data) => {
console.log(data);
return attendance("Louis"); })
.then((data) => {
console.log(data);
return attendance("Stepheny"); })
.catch((error) => {
console.log(error); })
JavaScript Promise.all() method
The Promise.all() JavaScript method lets you execute multiple asynchronous operations concurrently. In such a scenario, the callback will be executed when the Promise.all method completes the specified operations.
Example: using JavaScript Promise.all() method
The provided example will simultaneously execute the promises “x”, “y”, and “z”. After that, all of the promises will return “name”:
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve(name);
}, 2000);
});}
const x = promiseObj("Taylor");
const y = promiseObj("Stepheny");
const z = promiseObj("Max");
Promise.all([x,y,z])
.then((data) => {
console.log(data); });
The execution will only take two seconds for displaying three names, while in case of promise chaining it will require six seconds:
JavaScript Promise.race() method
If you want to execute the callback as soon as the first asynchronous operation is complete, you can utilize the “Promise.race()” method.
Example: Using JavaScript Promise.race() method
We have created three promises objects “x”, “y”, and “z” with the name and time arguments passed to the “promiseObj()” function:
return new Promise((resolve, reject) => {
setTimeout(() => {
return resolve(name);
}, time);
});}
Here, “Marie” has the least time of “1” second, so she is going to win the race and her name will be shown as output:
const y = promiseObj("Stepheny", 2000);
const z = promiseObj("Marie", 1000);
Promise.race([x,y,z])
.then((data) => {
console.log(data); })
.catch((error) => {
console.log(error);
})
The above-given output signifies that we have successfully implemented the Promise.race() method for executing multiple operations simultaneously.
Conclusion
Using the catch() and then() methods, you can handle the error thrown or reject() call in Promise Chaining. To handle errors, it is preferable to add a catch() method in your code. The error handler then examines the code and handles them accordingly. This write-up explained the Promise Error Handling in JavaScript with the help of suitable examples.