What do you make of PROMISES in ES6?

JS synchronous asynchronous understanding, and work in common use scenarios reference answer

Js is single-threaded, that is to say, can only complete one task at a time, in order to solve this problem, js task execution mode can be divided into two kinds, synchronous and asynchronous, we deal with in the es5 asynchronous can only be processed by means of the callback, in multilayer asynchronous callback will be one layer nested, known as the callback hell, Promise is a solution to asynchronous programming

Promise

Features:

  • This is a big pity. The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation, which has three states, namely, pendding, fulfilled, and Rejected.
  • This is a big pity. Once the state changes, it will not change again. There are only two possibilities for the change of the state, which is gradually forgotten

Basic usage:

const promise = new Promise(function(resolve, reject) { // ... Resolve (value); resolve(value); // this will be a big pity} else {reject(error); // Change the state from Pendding to Rejected}});Copy the code

After the Promise instance is generated, you can use the THEN method to receive the Resolved and Rejected state callback functions

promise.then( ()=> {
    console.log('resolved')    
}, () => {
    console.log('rejected')    
})
Copy the code

The Promise prototype has a catch method, an alias to Rejection, that specifies the callback when an error occurs

promise.then( ()=> {
    console.log('resolved')    
}, () => {
        console.log('rejected')    
}).catch( (err) => {
        console.log('catch')    
})
Copy the code

The promise prototype has finally methods on it for actions that will be performed regardless of the final state of the Promise object

 promise.then( ()=> {
        console.log('resolved')    
}, ()=> {
        console.log('rejected')
}).finally( (err) => {
        console.log('end')    
})
Copy the code

Promise.all

The promise.all method is used to wrap multiple Promise instances into a new Promise instance

Simple use:

const p = Promise.all([p1, p2, p3]);
Copy the code

Features:

The parameters are all promise instances, If the promise. Resolve method is not called to change it into the prize state of PROMISE instance P, the state of the incoming promise instance will be fulfilled, and the P state will be fulfilled The promise instance state changes to Rejected, and the P state changes to Rejected