Promises

Starting with ECMAScript 6, JavaScript has added support for Promise objects, which allow you to control the flow of delayed and asynchronous operations.

Promise objects have the following states:

  • Pending: Indicates the initial state, that is, the performance is being performed without the pity or rejected state.
  • This is a big pity: I will complete the operation successfully.
  • Rejected: Indicates that the operation is not completed.

Because the promise.prototype. then and promise.prototype. catch methods return promises, they can be called chained.

The chain call to Promise

We can use promise.then(), promise.catch(), and promise.finally() to associate further actions with a promise that becomes a finalised state. These methods also return a newly generated Promise object, which can be used optionally to make chain calls, like this:

const myPromise = (new Promise(myExecutorFunc)) .then(handleFulfilledA,handleRejectedA) .then(handleFulfilledB,handleRejectedB) .then(handleFulfilledC,handleRejectedC); // Alternatively, it might be better... const myPromise = (new Promise(myExecutorFunc)) .then(handleFulfilledA) .then(handleFulfilledB) .then(handleFulfilledC) .catch(handleRejectedAny);Copy the code

The promises in the chain call are nested, like matryoshka dolls, but also like a stack, each of which must be popped off the top. The first promise in the chain call is the deepest nested and will be the first to be popped.

(promise D, (promise C, (promise B, (promise A) ) ) )
Copy the code

A static method

Promise.all(iterable)

This method returns a new promise that will succeed only if all of the iterable promise objects succeed, or if any of the iterable promise objects fail. The new Promise object, after firing the success state, returns the success callback with an array of all the promise returns from iterable, in the same order as the iterable. If the new Promise triggers a failed state, it treats the error message from the first promise in iterable that triggers a failed state as its failed error message. The promise.all method is often used to process sets of states for multiple Promise objects. (See jquery.when method)

Promise.allSettled(iterable)

This is a big pity. Wait until all promises are settled. Each promise is fulfilled or rejected. Return a promise that completes after all promises have completed. With an array of objects, each corresponding to the result of each promise.

Promise.any(iterable)

Receives a collection of Promise objects, and when one Promise succeeds, returns the value of that successful Promise.

Promise.race(iterable)

When any child promise in the Iterable argument succeeds or fails, the parent promise immediately calls the parent promise’s binding handle using the child promise’s success return value or failure details as arguments and returns the promise object.

Promise.reject(reason)

Return a Promise object with a failed state and pass the given failure information to the corresponding handler

Promise.resolve(value)

Returns a Promise object whose state is determined by the given value. If the value is thenable(that is, the object with the THEN method), the final state of the returned Promise object is determined by the then method execution; Otherwise (the value is empty, a basic type, or an object with no THEN method), the Promise object will be returned with the state of FULFILLED and the value will be passed to the corresponding THEN method. In general, if you don’t know if a value is a Promise object, use promise.resolve (value) to return a Promise object so that the value can be used as a Promise object.

methods

Promise.prototype.catch(onRejected)

Add a Rejection callback to the current promise and return a new promise. When this callback function is called, the new Promise will be resolved with its return value. Otherwise, if the current promise enters the fulfilled state, the fulfilled result of the current promise will be the fulfilled result of the new promise.

Promise.prototype.then(onFulfilled, onRejected)

Add the fulfillment and rejection callback to the current promise, returning a new promise that resolves with the return value of the callback.

Promise.prototype.finally(onFinally)

Add an event-handling callback to the current Promise object and return a new promise object after the original promise object has resolved. The callback will be invoked after the current Promise is fulfilled or failed. This is a big pity.

Example of performing a catch(to throw a failure in a chain operation) :

New Promise((resolve, reject) => {console.log(' initialize '); resolve(); }). Then (() => {throw new Error(' something wrong '); Console. log(' execute 'this' '); }).catch(() => {console.log(' execute 'that '); = > {}). Then ((). The console log (' execution "this", no matter what has happened to the front '); });Copy the code

The following output is displayed:

Initialize execute "that" execute "this", no matter what happened beforeCopy the code

The sample

This example demonstrates some of the mechanics of Promise. The testPromise() method, called each time the button is clicked, creates a Promise object that uses window.setTimeout() to make the promise wait anywhere from 1 to 3 seconds to populate the data (through the math.random () method).

The populated Promise values are logged, and the log information shows how synchronous and asynchronous code in a method is decoupled through promises.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Width =device-width, initial-scale=1.0"> <title>Document</title> <style> #log{border: 1px solid #ddd; } < / style > < / head > < body > < div id = "log" > < / div > < div > < button onclick = "testPromise ()" > click < / button > < / div > < / body > < script > var promiseCount = 0; function testPromise() { let thisPromiseCount = ++promiseCount; let log = document.getElementById('log'); Log. insertAdjacentHTML('beforeend', thisPromiseCount + ') starts (<small> sync code starts </small>)<br/>'); // Create a new Promise instance: Use promises to increse the counter by one every time, Let p1 = new Promise(resolver (resolve, resolver)) Reject) => {log.insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise start (<small> asynchronous code start </small>)<br/>'); // Create an asynchronous call to window.setTimeout(function() {// populate Promise resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); }); Function (val) {return (val) {return (val) {return (val) {return (val); Log. insertAdjacentHTML('beforeend', val + ') Promise is filled (<small> asynchronous code end </small>)<br/>'); }). Catch (// record the failure reason (reason) => {console.log(' handle failed promise ('+reason+')'); }); Log. insertAdjacentHTML('beforeend', thisPromiseCount + ') Promise made (<small> sync code end </small>)<br/>'); } </script> </html>Copy the code