Basic Concepts of Promise

Promise came along to solve the problem of callback hell (nested inverted pyramid) that asynchronous programming created.

Const arr = [1,2,3]; const arr = [1,2,3]; arr.forEach((item) => { console.log(item); }); After the console. The log (' foreach '); SetTimeout (()=> {}, 1000);Copy the code
  1. Promise constructor

    Executor is a two-parameter function that takes resolve and reject. Executors typically trigger asynchronous operations that resolve the promise once the operation completes successfully and reject it if it fails. If an executor function throws an exception, the Promise state changes to Rejected. State can only be changed by resolve, reject, or throw Error

     a = new Promise((resolve, reject) => {
        throw 'qqq';
     })
     Promise {<rejected>: "qqq"}
     
     a = new Promise((resolve, reject) => {
        reject('qqq');
     })
     Promise {<rejected>: "qqq"}
     
     a = new Promise((resolve, reject) => {
        resolve('qqq');
     })
     Promise {<fulfilled>: "qqq"}
     
     a = new Promise((resolve, reject) => {
        return 'qqq';
     })
     Promise {<pending>}
    Copy the code
  2. Promise object

    The object represents the final completion state of an asynchronous operation and its resulting value. A promise object can only change state once, and there must be one result data. A Promise must be in one of the following states:

    • Pending: The initial state that has not been redeemed or rejected.

    • This is a pity: which means that the operation will be completed successfully.

    • Rejected: Indicates that the operation fails.

        pending -> fulfilled
        pending -> rejected
      
        a = new Promise((resolve, reject) => {
           resolve('aaa');
           reject('qqq');
           console.log('hhh');
        });
      
        hhh
        Promise {<fulfilled>: "aaa"}
        
        
      Copy the code

The chain call to Promise

The then, catch,finally methods associate further actions with a promise that has become a finalized state, and these methods return a newly generated Promise object. The termination state of these functions determines what the next Promise’s settled state will be in the chained call. Any termination that is not a throw creates an Resolved state, and termination with a throw creates a “rejected” state.

a = Promise.resolve(2).then(() => {}, () => {})
Promise {<fulfilled>: undefined}

a = Promise.resolve(2).then(() => { return 2; })
Promise {<fulfilled>: 2}

a = Promise.resolve(2).then(() => { throw 2; })
Promise {<rejected>: 2}
Copy the code

The nextValue returned may be another Promise object, in which case the promise is dynamically inserted into the chain call.

When there is no function in.then() that returns a promise object, the chain call proceeds directly to the next operation. Thus, a chain call can omit all handleRejection until the last.catch().

const myPromise =
  (new Promise(myExecutorFunc))
  .then(handleFulfilledA,handleRejectedA)

const myPromise =
  (new Promise(myExecutorFunc))
  .then(handleFulfilledA)
  .catch(handleRejectedAny);
Copy the code

Since there is no way to know the final state of the promise, no arguments are taken in the finally callback function, which is only used when the final result is to be executed regardless.

  • And Promise. Resolve (2). Then (() = > {}, () = > {}) (for the results of resolvedundefinedResolve (2).finally(() => {}) resolved2.
  • Similarly, Promise. Reject (3). Then (() = > {}, () = > {}) (for the results of fulfilledundefinedReject (3).finally(() => {})rejected3.

The method of Promise

Promise.all waits for everything to complete or the first one to fail. If the argument passed is an empty iterable, return a Promise that the already Resolved state is completed.

If the parameters contain non-promise values, those values are ignored and, if successful, are still placed in the return array.

Var p = Promise. All ([1, 2, 3]); Promise { <state>: "fulfilled", <value>: Array[3] } var p2 = Promise.all([1,Promise.resolve(444)]); Promise { <state>: "fulfilled", <value>: Array[2] } var p3 = Promise.all([1,Promise.reject(555)]); Promise { <state>: "rejected", <reason>: 555 }Copy the code

The promise.race (iterable) method returns a Promise that is resolved or rejected once a Promise in the iterator is resolved or rejected. If the passed iteration is empty, the returned promise will wait forever.