ES6中promise

1. What is promise

Promise is an asynchronous solution. It is essentially a constructor function. It includes methods such as all, reject, and resolve. Its prototype also includes then and catch methods. Promise has two major characteristics: First, the state of the object is not affected by the outside world. It has three states, namely pending (in progress), fulfilled (successful) and rejected (failed), only the result of the asynchronous operation can be determined. Second, the state change is finalized, that is, pending becomes fulfilled and pending becomes rejected. As long as these two changes occur, it will never change again.

2. resolve and reject

Resolve and reject can be regarded as a callback for promises. resolve is a callback for the success of the promise, and reject is a callback for failure. The reason is that resolve will change the state to fulfilled, and reject will change the state to rejected. Let's take a look at a new promise. This is mainly to get the corresponding data when .then or .catch. The then method can accept two parameters, the first corresponds to the callback of resolve, and the second corresponds to the callback of reject.image.png

Three, catch

catch is mainly used to catch exceptions, the same as the second parameter in .then in the previous step, as follows:

image.png

In this case, when an error occurs, it can enter the catch, and it will not affect the normal operation of others.

4. all

This method provides the ability to execute asynchronous operations in parallel, and execute callbacks only after all asynchronous operations have been executed and the results are successful. as shown in the image below

image.png

The corresponding callback will only be executed if all step results are successful.

image.png

Five, race

Contrary to the all method, in the race method, whoever finishes executing first will execute the corresponding callback.

image.png

image.png

Guess you like

Origin juejin.im/post/7084124909059702792