Reject a Promise in JavaScript
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.
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard