1. Reasons for Es6 to join promise

Pre-knowledge:

  • Asynchronous operations are necessary:

In synchronous operations (which can be executed only after the previous instruction has completed), long operations freeze the page, so it is necessary to make computationally intensive operations asynchronous.

  • Previous solutions for asynchronous operations:

1. Event monitoring:

Eg: Click event-document.click (callback function).

Disadvantages: If you miss the event, and then to monitor, is not the result.

2. Callback function:

Disadvantages: Easy to create callback hell; Code is hard to maintain; Poor readability;

2. Promise

2.1 What is Promise?

Promise is a solution to ES6 asynchronous programming that is more reasonable and powerful than traditional solutions (callback functions and event listeners).

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way.

2.2 Promsie role

  • Express asynchronous operations as a flow of synchronous operations, avoiding layers of nested callback functions.
  • Queue asynchronous operations, execute them in the desired order, and return the expected results.
  • Promises can be passed and manipulated between objects to help us deal with queues.

2.3 Promise syntax

let p1= new Promise(resolve, reject) = >/ /... Asynchronous operations
    if(/* Asynchronous operation succeeded */){
        resolve(value);
    } else {
        reject(error);
    } } )
    p1.then(function(value) {
        // Resolve state callback function
    }, function(error) {
        Reject state callback function
    })
Copy the code

2.3 Promise characteristics

  • The status of an object is not affected

The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. Only the resolve and reject functions can change the state. No other operation can change the state.

  • Once the state changes, it never changes again, and you can get this result at any time
  • The Promise is executed immediately after it is created
  • The code in the Promise constructor executes synchronously, whereas promise.then () is asynchronous.
  • A call to resolve or Reject does not terminate the execution of the code after the Promise argument function, or if there is a return.

2.4 Resolve and Reject Parameters

Normal value (non-promise value) : Passes the value to the callback function in THEN ().

Another Promise instance object (shown below) :

State transfer: the state of P1 is then passed to P2, and the state of P1 determines the state of P2. If P1’s state is pending, p2’s callback waits for p1’s state to change. If P1 is in resolved or Rejected, the P2 callback will be executed immediately.

3. The Promise prototype approach

3.1 Promise. Prototype. Then ()

Parameters:

Resolved callback function [Optional]

The callback function of the Rejected state

The return value:

A new Promise instance – so it can be chained, with a then method followed by a call to another THEN method.

Function:

Add a callback function for state changes to the Promise instance.

Promise value through

The parameters of promise.then () or.catch() are expected to be functions, and passing non-functions will result in value penetration.

When we do not put arguments in then or arguments that are not functions, for example: Promise.then (). Then (),promise.then(1),promise.then(promise.resolve (‘foo’)). If the argument in then() is not a function, then() is ignored.

Promise.resolve('foo')
    .then(Promise.resolve('bar'))
    .then(res= >{ console.log(res) })
    // 'foo'
Copy the code
Promise.resolve('foo')
    .then(() = >{ return Promise.resolve('bar') })
    .then(res= >{ console.log(res) })
    // 'bar'
Copy the code
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log)
/ / 1
Copy the code
Promise.resolve(1)
.then(function(){return 2})
.then(Promise.resolve(3))
.then(console.log)
/ / 2
Copy the code
Promise.resolve(1)
.then(function(){return 2})
.then(function(){
   return Promise.resolve(3)
})
.then(console.log)
/ / 3
Copy the code

A chain call to promise.then ()

When we use promises, when we return a value in the THEN function, we get whatever value in the next THEN. This is called a chain call to the THEN.

Promise.reject() and promise.prototype.catch () priority questions

The first THEN accepts two functions. The second then is a callback on failure. Since the first THEN does not raise an Error, the second THEN state is resolve. The failed callback state function is run when both the failed callback state function and the catch function exist. If the then method does not specify a failed callback, then specifies a failed callback. Exception penetration of a catch is passed down layers rather than a failed state being passed directly to the catch.

3.2 Promise. Prototype. The catch ()

The promise.prototype.catch () method is an alias for. Then (null, Rejection) or. Then (undefined, Rejection) that specifies the callback when an error occurs.

3.3 Promise. Prototype. Finally ()

The finally() method is used to specify actions that will be performed regardless of the final state of the Promise object.

Arguments: Callback function without arguments.

Implementation:

Promise.prototype.finally = function (callback) {
    let P = this.constructor;
    return this.then( value= > P.resolve(callback()).then(() = > value),
    reason= > P.resolve(callback()).then(() = > { throw reason }) );
};
Copy the code

4. Promise object methods

4.1 Promise. Resolve ()

Action: Returns an instance of a Promise in the Resolved state. The callback is executed immediately.

Parameter return value:

  • Promise instance – Returns this instance intact without any modifications.
  • Thenable object (object with then method) – Turn this object into a Promise object and immediately execute thenable object’s THEN () method.
  • Not an object with a then() method, or not an object at all – return a new Promise object in the resolved state and pass this parameter to the state callback.
  • Return an Resolved Promise object with no arguments.

4.2 Promise. Reject ()

Function: Returns an instance of a Promise whose state is Rejected. The callback is executed immediately.

The arguments of the promise.reject () method are left as reject arguments and become arguments for subsequent methods.

4.3 Promise. Try ()

Function: allows synchronous functions to execute synchronously and asynchronous functions to execute asynchronously. You can use promise.catch() to catch all synchronous and asynchronous errors.

const f = () = > console.log('now');
Promise.try(f);
console.log('next');
// now
// next
Copy the code

4.4 Promise.all() — Return complete if all are completed, return failure if one is failed

Effect: Wrap multiple Promise instances into a new Promise instance.

Parameters: an array of Promise instances

  • If it is not, the promise.resolve method is called first, the parameter is turned into a Promise instance, and further processing is done.
  • The arguments may not be arrays, but they must have an Iterator interface and each member returned is a Promise instance.

The return value:

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

The state of P is determined by P1, P2 and P3, which can be divided into two cases.

(1) Only when the states of P1, P2 and P3 become depressing, the state of P will become depressing. At this time, the return values of P1, P2 and P3 will form an array and be passed to the callback function of P.

(2) As long as p1, P2 and P3 are rejected, P becomes rejected, and the return value of the first rejected instance is passed to p’s callback function.

4.5 Promise.any() — Return complete if there is one completion, return failure if there are all failures

Effect: Wrap multiple Promise instances into a new Promise instance.

Parameters: an array of Promise instances

Note: Promise.any() is like the promise.race () method, except that promise.any () does not end when a Promise changes to the Rejected state. You must wait until all the parameters Promise become rejected.

The return value:

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

(1) As long as one of P1, P2 and P3 is fulfilled, THE state of P will become fulfilled. At this time, the return value of the first fulfilled instance will be passed to the callback function of P.

(2) P changes to Rejected only when the status of P1, P2 and P3 changes to Rejected. In this case, the return values of P1, P2 and P3 form an array and are passed to the callback function of P.

4.6 Promise.allSettled() — Return success when all ends

Effect: Wrap multiple Promise instances into a new Promise instance.

Parameters: an array of Promise instances

Return value: Wrapping the instance will not end until all of these parameter instances return the result (either pity or Rejected).

This will be a pity once it is over, and will not become rejected. After the state becomes fulfils, the Promise listener receives an array of parameters, each member of which is an object corresponding to two Promise instances passed in promise.allSettled (). Each object has a status attribute, whose value can only be the string fulfilled or the string Rejected. Someday,, the object has a value attribute, and the object has a reason attribute, which corresponds to the return values of two states, namely, rejected.

Note: The promise.allSettled () method is useful when we don’t care about the outcome of asynchronous operations, only if they end.

4.7 promise.race () — Returns the first state when there is a changed state

Effect: Wrap multiple Promise instances into a new Promise instance.

Parameters: an array of Promise instances

Return value: The state of the return value changes as long as one of the parameters array instance objects changes state first. The return value of the first changed Promise instance is passed to the callback function.

Reference:

es6.ruanyifeng.com/#README

www.cnblogs.com/xjt31/p/140…