Reject a Promise in JavaScript

Apr 16, 2020

The Promise.reject() function is the most concise way to create a rejected promise that contains a given error. You should then use .catch() to handle the error.

const p = Promise.reject(new Error('Oops!'));

return p.catch(err => {
  err.message; // 'Oops!'
});

With the Promise Constructor

When you create a promise using new, you call the Promise constructor. The Promise constructor takes a single parameter, an executor function. The Promise constructor then executes the executor function with 2 arguments: resolve() and reject().

function executor(resolve, reject) {
  typeof resolve; // 'function'
  typeof reject; // 'function'
}

new Promise(executor);

To reject a promise from the executor function, you should just call reject() with an error object.

const p = new Promise((resolve, reject) => {
  reject(new Error('Oops!'));
});

return p.catch(err => {
  err.message; // 'Oops!'
});

Reject With Non-Error

You can reject a promise with any value, not just an error object.

const p = Promise.reject(42);

return p.catch(err => {
  err; // 42
});

However, many libraries and frameworks assume that promises are always rejected with an error. So you should be careful if you choose to call Promise.reject() with a value that isn't an error.


Async/await is the future of concurrency in JavaScript. "Mastering Async/Await" teaches you how to build frontend and backend apps using async/await in just a few hours. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!