Detailed explanation of Promises in JavaScript

Detailed explanation of Promises in JavaScript

Promise is a solution for asynchronous programming. It is an object that can obtain messages of asynchronous operations. It greatly improves the difficulties of asynchronous programming and avoids callback hell. It is more reasonable and powerful than traditional solutions such as callback functions and events.

Syntactically, a Promise is an object that can receive messages from asynchronous operations. Provides a unified API so that various asynchronous operations can be handled in the same way

1. Promise instances have three states:

(1) Pending

(2) Resolved

(3) Rejected

2. Promise instances have two processes

(1) pending > fulfilled: resolved

(2) pending > rejected: Rejected

Note: Once the status changes from purchase and sales to other status, the status can never be changed.

Basic usage of Promise:

1. Create a Promise object

The Promise object represents an asynchronous operation and has three states: pending (in progress), fulfilled (successful), and rejected (failed)

The Promise constructor accepts a function as a parameter, the two parameters of which are resolve and reject.

2. Promise method

Promise has five common methods:

(1)then()

The then method can receive 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 reject callback function.

Another function is that when executing the resolve callback function, if an error occurs and an exception is thrown, the execution will not stop 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 can complete and perform tasks. It receives an array, and each item in the array is a Promise object. When all the Promise states in the array reach resolved, the state of the all method will become resolved, if there is a state that becomes rejected. Then the status of all methods will become 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 result is: [1,2,3] 
})

(4) receive()

The receive method is the same as all, and the received parameter is an array of Promises, but unlike all, when the first event is executed, the value of the promise object is directly returned.

The actual function of rece: When you want to do something but give up after 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 an operation that will be performed regardless of the final state of the Promise object. (This method is introduced in ES2018 standard)

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

The callback function of the finally method does not accept any parameters, which means there is no way to know whether the previous Promise status is fulfilled or rejected.

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

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

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • A Deep Dive into JavaScript Promises
  • Front-end JavaScript Promise
  • JS 9 Promise Interview Questions
  • How to add abort function to promise in JS
  • Thoroughly understand JavaScript's Promise

<<:  Pay attention to the use of HTML tags in web page creation

>>:  Optimizing the slow query of MySQL aggregate statistics data

Recommend

Writing High-Quality Code Web Front-End Development Practice Book Excerpts

(P4) Web standards are composed of a series of sta...

Uniapp uses Baidu Voice to realize the function of converting recording to text

After three days of encountering various difficul...

Explain how to analyze SQL efficiency

The Explain command is the first recommended comm...

5 Ways to Clear or Delete Large File Contents in Linux

Sometimes, while working with files in the Linux ...

js realizes two-way data binding (accessor monitoring)

This article example shares the specific code of ...

Detailed description of component-based front-end development process

Background <br />Students who work on the fr...

How to operate MySql database with gorm

1. Setting case sensitivity of fields in the tabl...

Causes and solutions to the garbled character set problem in MySQL database

Preface Sometimes when we view database data, we ...

Comprehensive understanding of html.css overflow

Comprehensive understanding of html.css overflow ...

How to configure mysql on ubuntu server and implement remote connection

Server: Ubuntu Server 16.04 LSS Client: Ubuntu 16...

Steps for Django to connect to local MySQL database (pycharm)

Step 1: Change DATABASES in setting.py # Configur...

Some summary of MySQL's fuzzy query like

1. Common usage: (1) Use with % % represents a wi...