On March 11, 2020, “One question of the Day series 🚀” by Wang Ergou blog: Dig gold, think not, Zhihu, Jane book, CSDN like again, form a habit, one question of the day series will be updated all the time, your support is the biggest motivation for me to continue to share 😘

Promise

Promise is a solution to asynchronous programming that is more reasonable and powerful than the traditional solution of callback functions and events.

With the Promise object, asynchronous operations can be expressed as a flow of synchronous operations, avoiding layers of nested callback functions.

The current state of a Promise must be one of the following three states: Pending, Fulfilled and Rejected. The change of the state can only be one-way and cannot be changed after the change.

A Promise must provide a THEN method to access its current value, final value, and reason.

The promise. Then (onFulfilled, onRejected) callback function can only be executed once and returns the Promise object

Each operation of a Promise returns a Promise object, which supports chained invocation.

The callback function is executed through the THEN method, and Promise’s callback is a microqueue placed in an event loop.

Promise can be used as follows (back to code) :

 function fn(){
     return new Promise((resolve, reject) = >Resolve (data), reject(error)})} fn(). Then (success1, fail1). Then (Success2, fail2)Copy the code

Promise.all

The promise.all () method is used to wrap multiple Promise instances into a new Promise instance.

Promise.all([promise1, promise2]).then(success1, fail1)
Copy the code

Success1 is invoked when both promisE1 and PROMISE2 are successful

Promise.race

The promise.race () method again wraps multiple Promise instances into a new Promise instance.

 Promise.race([promise1, promise2]).then(success1, fail1)
Copy the code

Promise1 and PromisE2 call Success1 whenever one of them succeeds

Tell yourself that even if you are tired, don’t forget to learn. There is no shortcut to success, only step by step. ‘!

If there is something wrong in the article, you are welcome to correct it.

Thank you ~ 💘