Promises are recognized from using

If we want to call a function, send a network request in this function.

  • If sending the network request is successful, inform the caller that the sending is successful, and return the relevant data ;
  • If the network request fails to be sent, the caller is notified of the failure and an error message .

If there is no Promise, you can indeed implement it yourself and get the corresponding callback. but,

  • We need to design the callback function by ourselves , the name of the callback function, and the use of the callback function;
  • Different people and different frameworks design different solutions. It is very troublesome for us to patiently read other people's source code or documents .

If you can define a standard and give the caller a promise, you can call back the data. Developers can use uniform standards to write similar codes, reducing learning costs. So Promise of ES6 is used to solve the dilemma of asynchronous code.

Table of contents

1. Understanding of Promise

2. Callback function Executor

3. The difference between different values ​​of resolve

4.then method

5.catch method

6. finally method

7. The resolve method

8. reject method

9. all method

10. allSettled method

11. race method

 12. any method


1. Understanding of Promise

Promise is a class that can be translated into promises , promises, and contracts;

When we need it, we can give the caller a promise : call back data to the caller after a period of time . In this case, a Promise object can be created;

When creating a Promise object through new, we need to pass in a callback function, which we call executor

  • This callback function will be executed immediately, and the other two callback functions resolve and reject will be passed in ;
  • When we call the resolve callback function , the callback function passed in by the then method of the Promise object will be executed ;
  • When we call the reject callback function , the callback function passed in by the catch method of the Promise object will be executed ;
const promise = new Promise((resolve, reject)=>{
    //调用resolve,那么then传入的回调会被执行
    resolve("成功信息")
    //调用reject,那么catch传入的回调会被执行
    reject("错误信息")
})

promise.then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})

During the use of Promise, we can divide it into three states:

  • When executing the code in the executor , it is pending : the initial state, neither honored nor rejected;
  • When resolve is executed , it is in the fulfilled state, and the Promise has been fulfilled: it means that the operation is successfully completed;
  • When reject is executed , it is in the rejected state, and Promise has been rejected: it means that the operation failed.

2. Callback function Executor

Executor is a callback function that needs to be passed in when creating a Promise. This callback function will be executed immediately , and two parameters are passed in:

new Promise((resolve, reject) => {
    console.log("执行executor代码")
})
Usually we will determine our Promise state in Executor:
  • Through resolve , the status of ( fulfilled ) Promise can be fulfilled , we can also call it resolved (resolved);
  • Through reject , you can reject ( reject ) the state of Promise;
Note here: Once the state is determined, the state of the Promise will be locked, and the state of the Promise cannot be changed
  • When we call resolve , if the value passed by resolve itself is not a Promise , then the state of the Promise will be changed to fulfilled (fulfilled) ;
  • When we call reject later, there will no longer be any response (not that this line of code will not be executed, but that the Promise state cannot be changed);

3. The difference between different values ​​of resolve

Case 1: If an ordinary value or object is passed in , this value will be used as the parameter of the then callback ;

new Promise((resolve, reject) => {
    resolve("normal resolve")
}).then(res =>{
    console.log("res:", res)
})

Case 2: If another Promise is passed in , the new Promise will determine the state of the original Promise ;

new Promise((resolve, reject) => {
    resolve(new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("第二个Promise的resolve")
        }, 3000)
      }))
}).then(res => {
    console.log("res:",res)
}).catch(err => {
    console.log("err:",err)
})

Case 3: If an object is passed in to resolve , and the object implements the then method , then the then method will be executed , and the state of the Promise will be determined according to the result of the then method :

new Promise((resolve, reject)=>{
    resolve({
        then: function(resolve, reject) {
            resolve("thenable value")
        }
    })
}).then(res => {
    console.log(res)
})

4.then method

The then method is a method (instance method) on the Promise object:

It is Promise.prototype.then placed on Promise's prototype

The then method accepts two parameters:

The callback function of fulfilled : the function that will be called back when the status becomes fulfilled;

Reject callback function : a function that will be called back when the state becomes reject;

const promise = new Promise((resolve, reject) => {
    resolve("resolve")
    reject("reject")
})

promise.then(res => {
    console.log("res:", res)
}, err => {
       console.log("err:", err)
   }
)

//等价于

promise.then(res => {
    console.log("res:", res)
}).catch(err => {
    console.log("err:", err)
})

Although the then method can accept two parameters, it is more readable to use the .catch method.

A Promise's then method can be called multiple times :
  • We can pass in the corresponding fulfilled callback for each call ;
  • When the state of Promise becomes fulfilled , these callback functions will be executed ;
promise.then(res=>{
    console.log("res1:", res)
})

promise.then(res=>{
    console.log("res2:", res)
})

promise.then(res=>{
    console.log("res3:", res)
})

5.catch method

The catch method is also a method (instance method) on the Promise object:
It is also Promise.prototype.catch placed on Promise's prototype
A Promise's catch method can be called multiple times:
  • We can pass in the corresponding reject callback for each call ;
  • When the state of Promise becomes reject, these callback functions will be executed ;
promise.catch(err => {
    console.log("err1:", err)
})
promise.catch(err => {
    console.log("err2:", err)
})
In fact, the catch method will also return a Promise object , so we can continue to call the then method or the catch method after the catch method :
For the following code, should the err2 print in the catch follow up, or the res print in the then?
promise.catch(err => {
    console.log("err1:", err)
}).catch(err => {
    console.log("err2:", err)
}).then(res => {
    console.log("res:", res)
})
The answer is res printing, because after the callback passed in by catch is executed, the default state will still be fulfilled ;
Then if we want to continue to execute the catch, we need to throw an exception:
promise.catch(err => {
    console.log("err1:", err)
    throw new Error("error message")
}).then(res => {
    console.log("res:", res)
}).catch(err => {
    console.log("err2:", err)
})

6. finally method

finally is a new feature added in ES9 (ES2018): it means that no matter whether the Promise object becomes fulfilled or rejected , the code will eventually be executed .
The finally method does not receive parameters , because it will execute regardless of whether it is in the fulfilled state or the rejected state
const promise = new Promise((resolve, reject) => {
    resolve("resolve")
    reject("reject")
})



promise.then(res => {
    console.log("res:", res)
}).catch(err => {
    console.log("err:", err)
}).finally(() =>{
    console.log("finally")
})

7. The resolve method

◼The then, catch, and finally methods we learned earlier all belong to the instance methods of Promise , and they are all stored on the prototype of Promise .
Next, let's learn about Promise class methods .
◼Sometimes we already have a ready-made content and want to convert it into a Promise for use . At this time, we can use the Promise.resolve method to complete it.
The usage of Promise.resolve is equivalent to new Promise , and the resolve operation is performed :
Promise.resolve("这样会简洁一点")

//等价于

new Promise((resolve) => {
    resolve("fulfilled")
})

8. reject method

The reject method is similar to the resolve method, except that the state of the Promise object is set to reject.
The usage of Promise.reject is equivalent to new Promise, but it will call reject:
Promise.reject("简洁")

//等价于

new Promise((resolve, reject) => {
    reject("reject")
})
Regardless of the form of the parameter passed in by Promise.reject, it will be directly passed to the catch as a parameter of the reject state.

9. all method

◼Another class method is Promise.all:
Its function is to wrap multiple Promises together to form a new Promise ;
The new Promise state is jointly determined by all the Promises in the package :
✓When all Promise states become fulfilled , the new Promise state will be fulfilled , and the return values ​​of all Promises will form an array ;
✓When a Promise status is rejected , the new Promise status will be rejected , and the return value of the first rejection will be used as a parameter ;
const promise1 = new Promise((resolve, reject) => {
    resolve("resolve")
    reject("reject")
})
const promise2 = new Promise((resolve, reject) => {
    resolve("resolve")
    reject("reject")
})
const promise3 = new Promise((resolve, reject) => {
    resolve("resolve")
    reject("reject")
})

Promise.all([promise1, promise2, promise3]).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})

10. allSettled method

The all method has a flaw: when one of the Promises becomes a reject state, the new Promise will immediately become the corresponding reject state.
Then for the resolved Promise and the Promise that is still in the pending state, we cannot get the corresponding result;
◼In ES11 (ES2020), a new API Promise.allSettled is added:
This method will only have a final state when all Promises have results (settled), whether they are fulfilled or rejected ;
And the result of this Promise must be fulfilled ;
//创建三个promise promise1 promise2 promise3
Promise.allSettled([promise1, promise2, promise3]).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})
◼Let 's take a look at the printed results:
The result of allSettled is an array, which stores the result of each Promise and corresponds to an object;
This object contains the status and the corresponding value ;

11. race method

If there is a Promise with a result, we want to determine the final state of the new Promise, then we can use the race method:
race means competition and competition , which means that multiple Promises compete with each other , and whoever gets the result first will use the result ;
//创建三个promise promise1 promise2 promise3

Promise.race([promise1, promise2, promise3]).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})

 12. any method

The any method is a new method in ES12, which is similar to the race method:
The any method will wait for a fulfilled state before determining the state of the new Promise ;
If all Promises are rejected , it will wait until all Promises become rejected ;
//创建三个promise promise1 promise2 promise3

Promise.any([promise1, promise2, promise3]).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})
◼If all Promises are rejected, an AggregateError error will be reported .

Guess you like

Origin blog.csdn.net/m0_51636525/article/details/125502482