JavaScript

JavaScript Promise Error Handling

Asynchronous code can use Promises for applying structured Error Handling. While using promises, you can specify an error handler to the “then()” method or use a “catch()” block. Similar to the exceptions added in the regular code, when a promise gets rejected, it looks for the nearest error handler, where thrown error is passed as a second parameter to then() method or the error handler passes it to catch() method.

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:

const promiseObj = new Promise((resolve, reject) => {
    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:

const promiseObj = new Promise((resolve, reject) => {
    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:

const attendance = function (name) {
    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”:

const promiseObj= function (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:

const promiseObj= function (name, time) {
  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 x = promiseObj("Taylor", 3000);
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.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.