How to use Promise.reject() in JavaScript? [SOLVED]


Written By - Olorunfemi Akinlua
Advertisement

Introduction to Promise.reject() method

In JavaScript, the promise.reject() method is used to create a new Promise object that is rejected with a specified reason. This method is typically used to signal that a promise has been unable to fulfill its intended purpose, such as when a network request fails or the desired value cannot be found. It is often used together with the promise.then() and promise.catch() methods, which allow you to specify what should happen when a promise is either fulfilled or rejected.

How to use Promise.reject() in JavaScript? [SOLVED]

 

In this article, we will discuss how to use the promise.reject() method in JavaScript with some examples.

 

Promises based on synchronous values

Sometimes, you may need to implement an existing Promise-based API and return a Promise from a function, even though the computation to be performed does not actually require any asynchronous operations. In that case, the static methods Promise.resolve() and Promise.reject() will do what you want. Promise.resolve() takes a value as its single argument and returns a Promise that will immediately (but asynchronously) be fulfilled to that value. Similarly, Promise.reject() takes a single argument and returns a Promise that will be rejected with that value as the reason. (To be clear: the Promises returned by these static methods are not already fulfilled or rejected when they are returned, but they will fulfill or reject immediately after the current synchronous chunk of code has finished running. Typically, this happens within a few milliseconds unless there are many pending asynchronous tasks waiting to run.)

It is possible, but unusual, to write a Promise-based function where the value is computed synchronously and returned asynchronously with Promise.resolve(). It is fairly common, however, to have synchronous special cases within an asynchronous function, and you can handle these special cases with Promise.resolve() and Promise.reject(). In particular, if you detect error conditions (such as bad argument values) before beginning an asynchronous operation, you can report that error by returning a Promise created with Promise.reject(). (You could also just throw an error synchronously in that case, but that is considered poor form because then the caller of your function needs to write both a synchronous catch clause and use an asynchronous .catch() method to handle errors.) Finally, Promise.resolve() is sometimes useful to create the initial Promise in a chain of Promises. We’ll see a couple of examples that use it this way.

 

Creating Settled Promises

When working your way through the examples in this book, you may want to key in and alter each example to gain practice. The static Promise.resolve() and Promise.reject() methods allow you to quickly create settled promises and see how the code works when you give it a different value.

For example, the following code creates a promise that’s already fulfilled with the value 10:

const promise = Promise.resolve(10);

promise.then((data) => {
  console.log(data);    // ⇒ 10
});

Here, we have a settled promise that represents only a known value. This promise will never be in the rejected state, so adding a rejection handler is pointless. To create a promise in the rejected state, we can pass a value to the Promise.reject() method, like this:

const promise = Promise.reject('Error!');

promise.then(null, (error) => {
  console.error(error);    // ⇒ Error!
});

This code creates a settled promise that’s rejected with a predefined value. If we add a fulfillment handler to this code, it will never be called.

Advertisement

 

Using the promise.reject method

Here is an example of using the Promise.reject() method to create a rejected promise:

const promise = new Promise((resolve, reject) => {
  const num = Math.random();

  if (num < 0.5) {
    resolve(num);
  } else {
    reject(new Error('Number is too large!'));
  }
});

promise.then(result => {
  console.log(`Number is ${result}.`);
}).catch(error => {
  console.error(error.message);
});

Output

Number is 0.17452706664245965.

In this example, we create a promise that generates a random number. If the number is less than 0.5, the promise is resolved with the number. Otherwise, the promise is rejected with an error. The then() method is used to handle the resolved promise, while the catch() method is used to handle the rejected promise.

Sure, here is another example that uses Promise.reject():

function fetchData(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open("GET", url);

        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(xhr.response);
            } else {
                reject(new Error(xhr.statusText));
            }
        };

        xhr.onerror = () => {
            reject(new Error("A network error occurred."));
        };

        xhr.send();
    });
}

fetchData(
    "<https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json>"
)
    .then((data) => {
        const parsedData = JSON.parse(data);
        console.log(parsedData);
    })
    .catch((error) => {
        console.error(error);
    });

Output

{
    "aliceblue": "#f0f8ff",
    "antiquewhite": "#faebd7",
    "aqua": "#00ffff",
    "aquamarine": "#7fffd4",
    "azure": "#f0ffff",
    "beige": "#f5f5dc",
    "bisque": "#ffe4c4",
    "black": "#000000",
    "blanchedalmond": "#ffebcd",
    "blue": "#0000ff",
    "blueviolet": "#8a2be2",
    "brown": "#a52a2a",
		....
    "turquoise": "#40e0d0",
    "violet": "#ee82ee",
    "wheat": "#f5deb3",
    "white": "#ffffff",
    "whitesmoke": "#f5f5f5",
    "yellow": "#ffff00",
    "yellowgreen": "#9acd32"
}

In this example, we have a function called fetchData() that sends an HTTP GET request to a color data URL. If the request is successful, the promise is resolved with the response data. Otherwise, the promise is rejected with an error. The then() and catch() methods are used to handle the resolved and rejected promises, respectively.

 

Summary

The Promise.reject() method is a method that creates a new Promise object that is rejected with a given reason. This can be useful when you want to signal that a Promise has failed and pass an error message or other information to the rejection handler

 

References

Promise.reject() - JavaScript | MDN (mozilla.org)

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment