In this tutorial, you’ll learn how to handle error in JavaScript promise. JavaScript promise are widely used to execute the code asynchronously and to make code execution faster. Assuming that you are familiar with what are JavaScript promises, in this tutorial you’ll see how to handle error when dealing with JavaScript promises in different scenarios.

Handle Error In JavaScript Promise When Making API Call

We generally tend to use JavaScript promise when making API calls. Let’s see an example where we need to make an API call. I’ll be making use of request-promise module to make API call.

const rp = require('request-promise');

rp({
    url :'https://jsonplaceholder.typicode.com/todos/1',
    method : 'GET'
})
.then((response)=>{
    console.log(response)
})
.catch(function (err) {
    console.log(`Error is ${err}`);
});

As seen in the above code, we have added a then block and catch block to handle resolve and reject of the above promise. The catch block handles error in the above JavaScript promise.

Handle Error In JavaScript Promise.all

There are scenarios when you have a bunch of JavaScript promises to handle inside Promise.all. If one of the promises breaks then it won’t execute further if not handled properly. So, let’s see how to handle error in JavaScript Promise.all.

const rp = require('request-promise');

function getPromise(i){
    return rp({
        url :'https://jsonplaceholder.typicode.com/todos/' + i,
        method : 'GET'
    })
}

let promises = [];
for(let i = 0;i <= 10; i++){
    promises.push(getPromise(i))
}

Promise.all(promises)
.then(function(response){
    console.log(`Response is ${response}`)
})
.catch(function(error){
    console.log(`Error is ${error}`);
})

As seen in the above code, the promise from getPromise method will get rejected for index 0 since it’s a non existing end point.

Now if you run the above code, Promise.all will stop at the very first rejection and won’t execute further. This may not be the expected behaviour. Sometimes, you may want the rest of the promise calls to be executed, irrespective of whether a particular promise is rejected or not.

While executing all promises inside Promise.all you need to handle error in individual promises. Modify the getPromise method with a catch block. Adding a catch to block to each promise makes sure that the Promise.all gets executed smoothly.

function getPromise(i){
    return rp({
        url :'https://jsonplaceholder.typicode.com/todos/' + i,
        method : 'GET'
    })
    .catch(function(error){
        return JSON.stringify({"error" : error.message || "error occured"})
    })
}

Here is how the entire code block looks :

const rp = require('request-promise');

function getPromise(i){
    return rp({
        url :'https://jsonplaceholder.typicode.com/todos/' + i,
        method : 'GET'
    })
    .catch(function(error){
        return JSON.stringify({"error" : error.message || "error occured"})
    })
}

let promises = [];
for(let i = 0;i <= 10; i++){
    promises.push(getPromise(i))
}

Promise.all(promises)
.then(function(response){
    console.log(`Response is ${response}`)
})
.catch(function(error){
    console.log(`Error is ${error}`);
})

Wrapping It Up

In this tutorial, you learnt how to handle error in JavaScript promise. We looked at two scenarios, one when dealing with a single promise call and when dealing with a bunch of promises inside Promise.all.

Do let us know your thoughts and suggestions in the comments below.