Detailed Explanation of Promise in JavaScript

  • 2021-11-29 23:00:25
  • OfStack

Basic usage of directory Promise: 1. Create Promise object 2. Summary of Promise method

Promise is a solution of asynchronous programming and an object, which can obtain the message of asynchronous operation, greatly improves the difficulty of asynchronous programming, avoids callback hell, and is more reasonable and powerful than the traditional solution callback function and event.

Syntactically speaking, Promise is an object that can get messages for asynchronous operations. A unified API is provided, and all kinds of asynchronous operations can be handled in the same way

1. An instance of Promise has three states:

(1) Pending (in progress)

(2) Resolved (Completed)

(3) Rejected (rejected)

2. The instance of Promise has two processes

(1) pending > fulfiled: Resolved

(2) pending > rejected: Rejected

Note: 1 Once you change from input and output status to other status, you can never change the status

Basic usage of Promise:

1. Create an Promise object

The Promise object represents an asynchronous operation with three states: pending (in progress), fulfilled (succeeded), rejected (failed)

The Promise constructor takes as an argument a function whose two arguments are resolve and reject

2. Promise method

Promise has five common methods:

(1) then ()

The then method can take two callback functions as parameters, the first callback function is called when the state of the Promise object changes to resoved, and the second callback function is called when the state of the Promise object changes to rejected. The second parameter can be omitted.


let promise = new Promise((resolve,reject)=>{
    ajax('first').success(function(res){
        resolve(res);
    })
})
promise.then(res=>{
    return new Promise((resovle,reject)=>{
        ajax('second').success(function(res){
            resolve(res)
        })
    })
}).then(res=>{
    return new Promise((resovle,reject)=>{
        ajax('second').success(function(res){
            resolve(res)
        })
    })
}).then(res=>{
 })

(2) catch ()

This method is equivalent to the second parameter of the then method, pointing to the callback function of reject.

Another function is that when executing the resolve callback function, if an error occurs, an exception is thrown, which will not stop the meteorite, but enter the catch method.


p.then((data) => {
     console.log('resolved',data);
},(err) => {
     console.log('rejected',err);
     }
); 
p.then((data) => {
    console.log('resolved',data);
}).catch((err) => {
    console.log('rejected',err);
});

(3) all ()

The all method completes and performs the task by receiving an array, each item of which is an Promise object. When all Promise states in the array reach resolved, the state of the all method changes to resolved, and if one state changes to rejected. Then the state of the all method becomes rejected.


javascript
let promise1 = new Promise((resolve,reject)=>{
	setTimeout(()=>{
       resolve(1);
	},2000)
});
let promise2 = new Promise((resolve,reject)=>{
	setTimeout(()=>{
       resolve(2);
	},1000)
});
let promise3 = new Promise((resolve,reject)=>{
	setTimeout(()=>{
       resolve(3);
	},3000)
});
Promise.all([promise1,promise2,promise3]).then(res=>{
    console.log(res);
    // The results are: [1,2,3] 
})

(4) rece ()

The rece method is similar to all 1. The parameters received are an array of Promise, but unlike all, the value of the promise object is returned directly after the first executed event is executed

The practical function of rece: When you want to do one thing and don't do it for a long time, you can use this method to solve it.


Promise.race([promise1,timeOutPromise(5000)]).then(res=>{})

(5) finally ()

The finally method is used to specify the action that will be performed regardless of the final state of the Promise object. (This method is the standard introduced in ES 2018)


promise
.then(result => { ... })
.catch(error => { ... })
.finally(() => { ... });

The callback function of the finally method takes no arguments, which means there is no way to know whether the previous Promise state is fulfilled or rejected


promise
.finally(() => {
  //  Statement 
});
//  Equivalent to 
promise
.then(
  result => {
    //  Statement 
    return result;
  },
  error => {
    //  Statement 
    throw error;
  }
);

In the above code, if you don't write the finally method, the same statement needs to be written once for success and once for failure. With finally method, you only need to write it once

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: