Promise to introduce

A PROMISE is an object from which you can get messages for asynchronous operations. There are all, race, reject, and resolve methods, and there are then and catch methods on the prototype.

Promise has two characteristics:

  • The state of an object is unaffected. Promise objects obtain asynchronous operations in three states: pending, fulfilled, or rejected. No operation can change this state except as a result of an asynchronous operation.
  • Once the state changes, it doesn’t change. This state will never change as long as it is fulfilled or rejected.

Shortcomings of the state:

You cannot cancel a Promise, it is executed as soon as it is created, and you cannot cancel it in mid-stream.

If you do not set the callback function, the Promise throws an error internally, which is not reflected externally.

When you are in the pending state, you have no way of knowing what stage you are currently in.

Use grammar:

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

// Resolve and reject are two functions

})

p.then(

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

()=>{} // Pass the reject function, reject translated into Chinese is to reject

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

Console. log(” Catch failed to execute callback throw reason “,reason)

})

Then method

The then method takes two arguments. The first argument is a callback if the Promise succeeds, and the second is a callback if the Promise fails. Only one of the two functions is called.

Callbacks added via.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) })Copy the code

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
})
Copy the code

The usage of catch

In parallel with the Promise object method then, there is a catch method for catching exceptions, similar to the try… The catch,

const p1 = new Promise((resolve,reject)=>{ var num = Math.random()*10 ; Console. log("num",num) if(num > 5){resolve(' > 5')}else{resolve(' > 5')}}) p1.then(res=>{reject(' > 5')}}) Console. log("res",res) // res > 5}). Catch (err=>{console.log("err",err) // err < 5}).Copy the code

All methods

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

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

The following is an example:

Const p1 = new Promise((resolve,reject)=>{resolve({name:' reject '})}) const p2 = 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"]})Copy the code

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 operations completes, regardless of whether the result is a success or failure. The rest of the operations do not enter race’s callback. The data returned depends on the data returned after the earliest execution.

Const p1 = new Promise((resolve,reject)=>{resolve({name:' reject '})}) const p2 = 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'}})Copy the code

Why use promises?

The advantages of the Promise

  • The way to specify callbacks is more flexible.
  • Support for chained calls, which can solve the callback hell problem. Callback hell is a nested call to the callback function, and the result of an asynchronous execution of the external callback function is the execution condition of the nested callback function. The downside of callback hell is that it is hard to read and exception handling.

The shortcoming of Promise

  • Promises cannot be cancelled, they are executed immediately, and cannot be paused or cancelled.
  • If the callback function is not set, the errors thrown by the Promise internally are not reflected externally.
  • When you are in the pending state, you have no way of knowing what stage you are currently in.