This content originally appeared on CodeSource.io and was authored by Deven
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.
The post How to use Promise.reject() in JavaScript appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-10-15T11:46:57+00:00) How to use Promise.reject() in JavaScript. Retrieved from https://www.scien.cx/2021/10/15/how-to-use-promise-reject-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.