1. Introduction of Promise

Promise object represents an asynchronous operation, has three states: pending, fulfilled, rejected, he has a characteristic, once the state changes, won’t change, at any time is the result of romise object state changes, there are only two possibilities: Changed from Pending to Resolved and from Pending to Rejected. As long as those two things happen, the state is frozen, it’s not going to change, it’s going to stay the same.

2. The characteristics of the Promise

Promise objects allow asynchronous operations to be expressed as a flow of synchronous operations, avoiding layers of nested callback functions, and Promise has some drawbacks. First, there is no way to cancel a Promise; once it is created, it is executed immediately and cannot be cancelled halfway through. Second, if you don’t set a callback function, errors thrown inside a Promise won’t be reflected externally. Third, when you are in a Pending state, you have no way of knowing what stage of progress you are currently in (just beginning or just finishing).

3. Create a Promise

As follows, you can create a promise

let promise = new Promise((resolve,reject) = > {})
Copy the code

There are two ways to call it

promise.then(onFulfilled,onRejected)
Copy the code
promise.then(onFulfilled).catch(onRejected)
Copy the code

4. Promise magical function

On the first code

async function test(num){
    try{
        await myPromise(num)
        console.log(num)
    }catch(e){
        console.log('Wrong')}}function myPromise(num){
    return new Promise((resolve,reject) = > {
        if(num < 0){
            resolve()
        }else if(num < 2){
            reject()
        }
    })
}
test(-1)
test(1)
test(3)
Copy the code

Promise combined with the blocking effect of async await. When executing myPromise function, the function execution will be suspended due to the use of await. Only when the promise process ends, The test function continues, whether it is resolve or reject. So the first function executes and prints -1, the second prints’ error, ‘and the third prints nothing because the promise hasn’t yet ended.

Let’s look at the second case:

var p1 = new Promise(function(resolve, reject){
  // ... some code
});
 
var p2 = new Promise(function(resolve, reject){
  // ... some code
  resolve(p1);
})
Copy the code

In the code above, p1 and P2 are both instances of Promise, but P2’s resolve method takes P1 as an argument, and p1’s state is passed to P2. If the state of P1 is pending, the p2 callback will wait for the state to change. If P1 is fulfilled with pity or Rejected, then P2’s callback function will be executed immediately, which indirectly acts as a blockade.