The purpose of the Promise

Promise is a solution to asynchronous programming that is more reasonable and normative than traditional solutions.

The three main benefits of promises over traditional approaches are:

  1. Specification of the name and order of the callbacks

  2. Avoid callback hell and make your code more readable

  3. Easy to catch errors

How do I create a New Promise

return new Promise((resolve,reject)=>{... })

Call resolve(result) if the task succeeds

Call Reject (error) if the task fails

Resolve and reject call success and failure functions

How to use promise.prototype.then

getData(1)
.then(function(x){
  console.log(x)
  return getData(2)
}, e=>{console.log(e)})
.then(function(x){
  console.log(x)
  return getData(3)
}, e=>{console.log(e)})
.then(function(x){
  console.log(x)
}, e=>{console.log(e)})
Copy the code

Then () takes two functions

The first function is executed on success and the second on failure

How do I use promise.all

Use promise.all when we need to get more data before we proceed to the next step:

Promise.all([func1(), func2(), func3()]).then()
Copy the code

Promise.all requires passing in an array of Promise objects. When each of these objects succeeds, the first function in then is executed, and when it fails, only the error data for the first failed Promise is retrieved

Promise. All is to reach the end together, one failure, all failure

How do I use promise.race

Promise.race corresponds to promise. all. Whichever Promise object gets the result the fastest is used first (as long as it’s fast, whether it fails or succeeds).