In Promise,reject
andcatch
There are two ways to deal with asynchronous operation failures. They have some important differences:
reject
:
reject
is a method of the Promise instance to explicitly transfer the Promise state frompending
Change torejected
, and pass a reason for rejection (usually an Error object or a value that describes the failure).
Once the Promise entersrejected
The status will trigger the Promise chain to follow immediately.reject
The first one behindcatch
Method or the nextthen
Failure handling function in the method (if any).
Example:
let promise = new Promise((resolve, reject) => { reject(new Error('Something went wrong')); }); (error => { (error); });
catch
:
catch
is a method of a Promise instance that registers functions that catch exceptions in the Promise chain. It only captures the Promise status asrejected
Scenario.
catch
Method receives a callback function, which enters in Promiserejected
The status is called and can be accessedreject
The reason for the rejection of the pass.
Example:
let promise = new Promise((resolve, reject) => { throw new Error('Something went wrong'); }); (error => { (error); });
Summary of the differences:
Trigger timing:
-
reject
Actively call during the execution of the Promise and explicitly change the Promise state torejected
。 -
catch
is a method registered in the Promise chain, used to capture and reachrejected
Promise of status.
usage:
-
reject
Used to handle errors during the execution of the Promise and pass them to subsequent handlers. -
catch
A callback function used to register errors in the Promise chain.
Chain call:
-
reject
It is an operation in the Promise executor function, and cannot be likecatch
Same chain call, because it does not return a Promise object. -
catch
Can be called in a chain, allowing possible errors in multiple steps in the Promise chain.
In practical applications, it is usually recommended to usecatch
Methods to handle exceptions in the Promise chain because it can more clearly separate error handling from chain calls, making the code more readable and maintained.
This is all about this article about the difference between reject and catch processing in promises. For more related content on reject and catch in promises, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!