How to use Promise.reject() in JavaScript
In JavaScript, Promises are used to denote an ongoing task which has not completed yet. It may Resolve with a result or Reject with an error. It can take an infinite amount of time to complete something internally.
A promise may have more promises within it. Promises can be chained one after the another to link dependent tasks or can be executed in parallel to speed up independent tasks. The promise structure also provides effective error-catching mechanisms.
Promise.reject():
When a promise finishes the attempt, it calls resolve if it was successful or reject if there was an error. Promise.reject() method returns a Promise object that is rejected with a given reason.
Syntax:
Promise.reject(‘rejectionReason’)
Example:
Promise.reject('failure')
.then((value) => {
console.log(value);
}).catch((error) => {
console.log(error); // "failure"
});
Instead of directly stating reason inside reject, you can also throw an instanceof an Error object. Also, reject expect only one argument (or none) and will ignore additional arguments. Once a promise is rejected, it is settled & will never execute again until explicitly called.