Promise to introduce

A Promise is an object from which you can retrieve messages for asynchronous operations. There are all, race, reject, and resolve methods, and there are then, catch, and so on.

Promise has two characteristics:

The state of the object is not affected by the outside world. The Promise object catches an asynchronous operation and has three states: pending(which is in progress), reject(which has succeeded), and reject(which has failed). This state cannot be changed by any operation other than the result of an asynchronous operation. Once the state changes, it doesn’t change. From “Pending” to “Fulfilling” and “Pending” to “Rejected”. As long as they are fulfilled and rejected, the state will not change. Disadvantages of statuses:

You cannot cancel the Promise, which is executed as soon as you create it, and cannot be canceled halfway.

If you don’t set the callback function, the Promise throws an error internally, but it doesn’t reflect on the outside.

In the pending state, it is impossible to know the current stage of progress.

Use grammar:

let p = new Promise( (resolve,reject)=>{

//resolve and reject are two functions

})

p.then(

()=>{}, // pass to the resolve function

()=>{} // reject () {// reject ()

).catch((reason,data)=>{

Console. Log (“catch failed callback throw reason “,reason)

})

Then method

The then method takes two arguments, the first being a callback if the Promise is successful and the second being a callback if the Promise fails, and only one of the two functions will be called.

Callbacks added through.then will be called at any time, and multiple callbacks can be added, running sequentially and independently at once.

Const p = new Promise ((resolve, reject) = > {resolve (" success ")}) p.t hen ((res) = > {the console. The log (res) / / return success}, (err) = > { console.log(err) })

With multiple callback functions

const p =new Promise((resolve,reject)=>{
 resolve(1)
})
p.then((res1)=>{
 console.log('res1',res1) // 1
 return res1 * 2;
}).then((res2)=>{
 console.log('res2',res2) //2
}).then((res3)=>{
 console.log('res3',res3) //undefined
 return Promise.resolve('resolve')
}).then(res4=>{
 console.log('res4',res4) //resolve
})

The usage of catch

In parallel to the Promise object method then, there is a catch method that catches exceptions, and a try… The catch,

const p1 = new Promise((resolve,reject)=>{ var num = Math.random()*10 ; Console. log("num",num) if(num > 5){resolve(' greater than 5')}else{reject(" less than 5")}}) p1. Then (res=>{ Log ("res",res) // res greater than 5}). Catch (err=>{console.log("err",err) // err less than 5}).

All methods

The all method means that all asynchronous operations are completed before the callback is executed, and the result is returned as an array of data, a combination of data returned by multiple requests. The same level as the THEN method.

Use syntax: promise.all ([p,p1,p2….] ).then()

Examples are as follows:

Const p1 = new Promise((resolve,reject)= new Promise((resolve,reject))}) const p2 = new Promise((resolve,reject)= new Promise((resolve,reject))}) const p2 = new Promise((resolve,reject)= new Promise((resolve,reject)) { Resolve ([' a ', 'b'])}) const p3 = new Promise ((resolve, reject) = > {resolve (' two fool ')}) Promise. All (/ p1, p2, p3). Then (res = > { The console. The log (res) / / [{name: "qian qian"}, [' a ', 'b'], "the two fool"]})

Race method

All waits for all asynchronous operations to complete before executing the callback. Race, on the other hand, starts executing the callback as soon as one of the asynchronous operations completes, whether it succeeds or fails. The rest of the callbacks do not enter Race’s callback. The data returned depends on the data returned after the earliest execution.

Const p1 = new Promise((resolve,reject)= new Promise((resolve,reject))}) const p2 = new Promise((resolve,reject)= new Promise((resolve,reject))}) const p2 = new Promise((resolve,reject)= new Promise((resolve,reject)) { setTimeout(()=>{ resolve(['a','b']) },1000) }) const p3 = new Promise((resolve,reject)=>{ setTimeout(()=>{ Resolve (' two fool ')}, 2000)}) Promise. Race (/ p1, p2, p3). Then (res = > {the console. The log (res) / / {name: 'qian qian'}})

Why use Promise?

The advantages of the Promise

  • The way you specify the callback function is more flexible.
  • Support for chained calls to solve the problem of callback hell. Callback hell is a nested callback function invocation. The result of the asynchronous execution of the external callback function is the execution condition of the nested callback function. The downside of callback hell is that it’s not easy to read and exception handling.

The shortcoming of Promise

  • You cannot cancel the Promise, which is executed as soon as you create it, and you cannot suspend or cancel it.
  • If you do not set the callback function, errors thrown inside the Promise will not be reflected outside.
  • When you are in the pending state, you cannot know what stage you are in.