Open In App

Promise reject does not propagate the error correctly in JavaScript

Last Updated : 29 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand why Promise’s reject() method doesn’t propagate the error correctly, and later we will see the solution for the same along with certain theoretical explanations and coding examples.

Let us first have a look into the following section quickly which enlightens us on the syntax of how a promise will be created.

Syntax: Following syntax, we may use in order to create a new promise which will either resolve or reject as per the need:

let promise_variable_name = new Promise ((resolve, reject) => {
    // Do something...
    // Either resolve it with certain parameters
    // inside resolve() method or either reject it
    // with reject statement in reject() method
});

Now we will have a look over the following shown syntax of then() as well as the catch() method which we will use to execute/catch an error received from the previously created promise:

promise_variable_name.then((result) => {
    // Do something with result parameter's value
})

// Further catch statement has to be added
// in case of any error caught
.catch((error) => {
    // Do something with this error variable
})

Now that we have seen all the syntaxes and analyzed them carefully let’s see a quick example that will help us to understand all in a very better and more efficient manner.

Example: In this example, we will create a promise using the above-shown syntax and execute them in order to display the result correctly over the console.

Javascript




<script>
    let promise = new Promise((resolve, reject) => {
        resolve("This article is available on "
            + "the GeeksforGeeks platform...");
    });
 
    promise
        .then((result) => console.log(result))
        .catch((error) => console.log(error));
</script>


Output:

This article is available on the GeeksforGeeks platform...

Now that we have seen the promise’s execution using the above example. Let’s have a look over the following examples in which we will try to analyze our problem statement as well as its solution.

Example 1: 

  • In this example, we will create a function that will accept a number (either positive or negative), and then we will create a promise through the above-shown syntax. 
  • Then inside that promise, we will apply a condition (with the help of an if-statement) which will check the number’s value as per the requirement. 
  • Then if that number matches the requirement, we will apply the reject() method that will contain a certain statement in itself. Afterward, we have added a line that is not required as an output on the console side but still, we have added it in order to see if and not our code works fine or not. 
  • Then at last we will call our method using both the then() method (for printing result) and catch() method (in order to catch the error caught, if so).

Javascript




<script>
    let checkNumValue = (num) => {
        return new Promise((resolve, reject) => {
            if (num === 0) {
                console.log("Zero number received...!!");
                reject("Stop code's execution since "
                    + "invalid number caught...");
            }
            console.log("This line is of no use, hence "
                + "not required in output...!!!");
        });
    };
 
    checkNumValue(0)
        .then((result) => console.log(result))
        .catch((error) => console.log("Caught Error: " + error));
</script>


Output:

Zero number received...!!
This line is of no use, hence not required in output...!!!
Caught Error: Stop code's execution since invalid number caught...

Now as we have seen that one unwanted line gets printed in the browser’s console which was not required here and the reason for the same is that when the reject() method is called, it will do the work and make the control flow goes on and it would stop it’s execution until something explicitly passed in after reject() method execution statement.

Example 2: 

  • In this example, we will take into consideration the previous example’s code and further, we will add certain changes in the function itself to make it executable as per the need. 
  • In this method after the reject() function call, we will add an empty return statement which will make the execution end or completed over that point itself and will not move further. 
  • With this return statement that one extra line gets omitted and will not be displayed over the browser’s console as an output.

Javascript




<script>
    let checkNumValue = (num) => {
        return new Promise((resolve, reject) => {
            if (num === 0) {
                console.log("Zero number received...!!");
                reject("Stop code's execution since "
                    + "invalid number caught...");
                return; // This line marks end of execution
            }
            console.log("This line is of no use, hence "
                + "not required in output...!!!");
        });
    };
 
    checkNumValue(0)
        .then((result) => console.log(result))
        .catch((error) => console.log("Caught Error: " + error));
</script>


Output:

Zero number received...!!
Caught Error: Stop code's execution since invalid number caught...


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads