Promise.reject()

  • JavaScript
  • Async
  • Promises
  • ES2021

We're nearing the end of the year and also getting close to the end of the Promise methods that are currently available. Today I'm going to take a brief look at Promise.reject(). This method is much simpler than the ones I've written about in the last few weeks. Where Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race() all take iterables of Promises and have various ways of handling the resolution or rejection of any or all Promises in that iterable, Promise.reject() is all about deliberately rejecting a single Promise. This method is useful for debugging or writing a Promise-based library, and it's one that I've used in examples for some of the Promise iterable methods.

Promise.reject() is pretty straightforward, it accepts a reason for rejecting and returns a Promise that rejects with that reason. It's recommended that you make the reason a proper Error to aid in debugging and error catching.

Syntax

Promise.reject(reason);

Parameters

  • reason - The reason why this Promise rejected.

Return Value

Promise.reject() returns a Promise that is rejected with the given reason.

Since the Promise returned by this method is rejected, if you attach the .then() instance method, the resolution handler function inside of .then() never runs, and instead the reason is passed to the rejection handler function.

Promise.reject(new Error("oh no, rejected!!!")).then(  (result) => {    console.log(result);  }, // This never runs  (error) => {    console.error(error);  });// Expected result: "Error: oh no, rejected!!!"

Similarly, we can use the .catch() instance method. As a reminder, .catch() is syntactic sugar on the .then() method that only passes on an error to the rejection handler function.

Promise.reject(new Error("oh no, rejected!!!")).catch((error) => {  console.error(error);});// Expected result: Error: oh no, rejected!!!

From MDN: The Promise.reject() method returns a Promise object that is rejected with a given reason.

See more examples and further documentation here.