es6 new Promise

Promise is a constructor, which has methods such as all, reject and resolve, and methods such as then and catch on its prototype.

Therefore, the object produced by Promise new must have then and catch methods.

The constructor of Promise receives one parameter, which is a function, and passes in two parameters: resolve and reject, which respectively represent the callback function after the asynchronous operation is successfully executed and the callback function after the asynchronous operation fails.

let p1 = new Promise((resolve, reject) => {
  resolve('成功')
})
 
let p2 = new Promise((resolve, reject) => {
  resolve('success')
})
 
let p3 = Promse.reject('error')
 
Promise.all([p1, p2]).then((result) => {
  console.log(result)               //['成功','success']
}).catch((error) => {
  console.log(error)
})
 
Promise.all([p1,p3,p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)      // 'error'
})

usage of reject

The then method can accept two parameters, the first corresponds to the resolve callback, and the second corresponds to the reject callback.

So we can get the data they passed over separately.

usage of catch

Same as the second parameter of then, it is used to specify the callback of reject.

Even if there is an error code, no error will be reported, and it has the same function as the try/catch statement.

Usage of the all method

The all method of Promise provides the ability to execute asynchronous operations in parallel, and the callback is not executed until all asynchronous operations are executed.

all will put the results of all asynchronous operations into an array and pass them to then, which can execute multiple asynchronous operations in parallel, and process all the returned data in one callback.

Special attention should be paid to the sequence of data in the array of successful results obtained by Promise.all and

The order of the array received by Promise.all is consistent, that is, the result of p1 comes first, even if the result of p1

Acquired later than p2. This brings a great benefit: in the process of front-end development requesting data,

Occasionally, you will encounter a scenario where multiple requests are sent and data is obtained and used according to the order of the requests.

Using Promise.all will undoubtedly solve this problem.

The following is used in the project: Because multiple forms are used in the page, the form is verified first when saving, and the save interface is triggered in the then() method only after each form is verified.

Guess you like

Origin blog.csdn.net/qq_36657291/article/details/129390058
Recommended