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

TypeScript Mapping Type Details

Table of contents 1. Mapped Types 2. Mapping Modi...

How to install MySQL 8.0 and log in to MySQL on MacOS

Follow the official tutorial, download the instal...

What you need to know about MySQL auto-increment ID

Introduction: When using MySQL to create a table,...

Methods and steps for Etcd distributed deployment based on Docker

1. Environmental Preparation 1.1 Basic Environmen...

A brief discussion on the problem of Docker run container being in created state

In a recent problem, there is such a phenomenon: ...

A brief discussion on HTML doctype and encoding

DOCTYPE Doctype is used to tell the browser which...

Tutorial on installing GreasyFork js script on mobile phone

Table of contents Preface 1. Iceraven Browser (Fi...

Undo log in MySQL

Concept introduction: We know that the redo log i...

How to implement line breaks in textarea text input area

If you want to wrap the text in the textarea input...

CSS3 implements the sample code of NES game console

Achieve resultsImplementation Code html <input...

Detailed explanation of nodejs built-in modules

Table of contents Overview 1. Path module 2. Unti...