What is the difference between reject and catch processing in promise?

`reject` and `catch` in `Promise` are both methods used to handle `Promise` exceptions, but there are some differences between them.

`reject` is a method of a `Promise` instance, used to change the status of a `Promise` object to `rejected`, and can pass a rejection reason as a parameter. The `reject` method returns a rejected `Promise` object whose `reason` property is the incoming rejection reason.

For example:

let promise = new Promise((resolve, reject) => {
  reject("error");
});

promise.then(
  (value) => {
    console.log(value);
  },
  (reason) => {
    console.log(reason); // "error"
  }
);

`catch` is a method of `Promise` instance, used to handle exceptions of `Promise` objects. It can accept a callback function as parameter, which is called when `Promise` is rejected, equivalent to `then(null, onRejected)`.

For example:

let promise = new Promise((resolve, reject) => {
  reject("error");
});

promise.catch((reason) => {
  console.log(reason); // "error"
});

As can be seen from the above example, both `reject` and `catch` play the same role in handling exceptions in `Promise` objects. However, there are still some differences between them:

1. `reject` can directly change the status of a `Promise` to `rejected`, while `catch` is just syntactic sugar for the `then` method, and `then(null, onRejected)` needs to be called in front to achieve the same effect. .
2. `catch` can handle all exceptions in the `Promise` object chain, while `reject` can only handle exceptions in the current `Promise` object.
3. `catch` can be called in a chain to handle exceptions of multiple `Promise` objects, while `reject` can only return a rejected `Promise` object.

Therefore, in general, we recommend using the `catch` method to handle `Promise` exceptions, because it can more conveniently chain calls and handle exceptions in the entire `Promise` chain.

Supongo que te gusta

Origin blog.csdn.net/qq_68299987/article/details/135439457
Recomendado
Clasificación