Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to prevent promises swallowing errors ?

How to prevent promises swallowing errors ?

In this article, we will try to understand how we may prevent the promises swallowing errors using several predefined techniques provided by JavaScript.

Before diving into the major topic of concern let us understand quickly how we may declare a promise using the following syntax.

Syntax:

let promise = new Promise((resolve, reject) => {
    ...
});

Example 1: The following code snippet will help us to understand promise declaration in a much better way:

Javascript




let promise = new Promise((resolve, reject) =>{
    resolve("Hello neveropen")
});
 
promise.then(result => console.log(result));


Output:

Hello neveropen

Now let us look into our problem statement with which we have to prevent promises swallowing errors. Consider the following code snippet (code example), in which a scenario is illustrated (which is based on real-time working) in which we implemented chaining of .then() method one after the another.

Now if we pass in some parameter that is though not declared anywhere in the code snippet then our promise will catch the error (as a Reference error) and immediately discards (or rejects) the promise and further results in code crashing.

Example 2: See the code snippet below

Javascript




let promise = new Promise((resolve, reject) => {
    resolve();
});
promise
    .then(function () {
        console.log("neveropen");
    })
    .then(function () {
        console.log("Hello ", someRandomText);
    });


 
 

Output:

 

 

Now as we may see in the above image’s output, the error is thrown out and thus the promise gets rejected, but we may don’t want that thing to happen, so one of our approaches could be like using one handler function which is chained just after the error which is received from previous .then() method. 

 

Example 3: See the code snippet below

 

Javascript




let promise = new Promise((resolve, reject) => {
    resolve();
})
 
promise
    .then(function () {
        console.log("neveropen");
    })
    .then(function () {
        console.log("Hello ", someRandomText);
    }, function (error) {
        console.log("Promise rejected, error message : ", error);
    });


Output:

As we may see this approach (of implementing one handler function) doesn’t seem to give us the correct result, therefore we may have to use the .catch() method after we have received the error.

Example 4: See the code snippet below

Javascript




let promise = new Promise((resolve, reject) => {
    resolve();
})
 
promise
    .then(() => {
        console.log("neveropen");
    })
    .then(() => {
        console.log("Hello", someRandomText);
    })
    .catch((error) => {
        console.log("Promise rejected,
            error message : ", error);
    });


Output:

This approach works fine and doesn’t reject the promise which we had declared for execution, instead, it actually fulfills the promise as its state and successfully printouts the error message without crashing the code.

Note: We may have seen successful prevention of promises from swallowing errors (in the above code snippet), but it’s not possible for us every time to chain .catch() with every .then() method having an error. Therefore while working on a project we first have to install the Bluebird, one of the most popular Promise libraries which has an inbuilt method (named onRejection handler) and also one another by default handler(called unhandledRejection) which help us to handle the unhandled rejection over the complete code snippet and this code snippet we have to implement it at once and after implementing it at once we need not worry about the unhandled exceptions at all.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments