In the previous article, we implemented the basic functionality of Promise and the then and catch instance methods. Let’s implement all the instance methods and static methods of the Promise object in ES6.

Source address, welcome to star🤭

  • Promise.prototype.finally()

This method executes the incoming callback regardless of the final state of the Promise object. Two things to say about the implementation of this method are that the callback of the 1.finally method does not take any parameters, which indicates that the execution of the callback does not depend on the state and result of the Promise. 2. Finally does not prevent the result from being passed. That is, if a finally method is followed by a chain-called then or catch method, the call continues. So a finally method should return a Promise whose result and state are the state and result of the Promise that called the finally method. It is natural to think of using THEN methods here, because THEN methods have exactly the properties described above, so finally methods are essentially special cases of THEN methods.

Promise.prototype.finally = function (onFinished) {
  return this.then((val) => {
    onFinished();
    return val;
  },(reason) => {
    onFinished();
    throw reason
  });
};
Copy the code
  • Promise.resolve()

The method returns a Promise object, the result and state determined by the input parameter.

Promise.resolve = function (value) {
  //返回promise对象
  return new Promise((resolve, reject) => {
    if (value instanceof Promise) {
      value.then(
        (res) => {
          resolve(res);
        },
        (reason) => {
          reject(reason);
        }
      );
    } else {
      //状态设置为成功
      resolve(value);
    }
  });
};
Copy the code
  • Promise.reject()

This method returns an instance of Promise with a state of Rejected. The state of the returned instance is always Rejected, no matter what the input parameter is.

Promise.reject = function (reason) {
  return new Promise((resolve, reject) => {
    reject(reason);
  });
};

Copy the code
  • Promise.all()

This method takes an array of Promise instances as arguments and returns a Promise. There are two cases of this Promise state. We will temporarily call the array of Promise instances ARR, and call the Promise returned by all P. 1. Only when the states of all members of ARR become depressing, THE state of P will become depressing, and the result will be the result of all members of ARR. 2. When a member of the ARR changes to Reject, p immediately changes to Rejected, and the result is the result of the member whose state changes to Reject.

Let isPromise = (x) => {typeof x === "object" &&x! = null) || typeof x === "function") { if (typeof x.then === "function") { return true; } } return false; }; Return new Promise((resolve, reject) => {// let count = 0; // let count = 0; // result array let arr = []; For (let I = 0; i < promises.length; I ++) {if (isPromise(promise [I])) {promise [I]. Then ((res) => {// Count++ // we can't use push here because we want the order of the result array to be the same as the order of the // promise array passed in. // With push, the order cannot be guaranteed because asynchronous operations return results at different speeds. arr[i] = res; If (count == promises. Length) {// Resolve (arr); }}, (reason) => {// The object status is failure, reject reject(reason); }); } else {// non-promise pushes directly into the result array count++; arr[i] = promises[i]; if (count === promises.length) { resolve(arr); }}}}); };Copy the code
  • Promise.race()

Method takes an array of Promise instances as arguments (arR) and returns a Promise(p). The Promise state and result are determined by the member who changes the state first in arR, that is, the state and result of P are the state and result of the member who changes the state first. If a member of the ARR is not a Promise instance, it is first turned into a Promise instance and then processed further.

Promise.race = function (promises) { return new Promise((resolve, reject) => { for (let i = 0; i < promises.length; I++) {// non-promise is converted to Promise if (! (promises[i] instanceof Promise)) { promises[i] = Promise.resolve(promises[i]); // resolve(v); // resolve(v); // resolve(v); // resolve(v); }, (r) => {// Modify the state of the returned object to "fail" reject(r); }); }}); };Copy the code
  • Promise.any()

This method takes an array of Promise instances as arguments (arR) and returns a Promise(p). This method behaves exactly the opposite of the promsie.all method. As long as one member of ARR becomes a depressing state, P will become a depressing state; When all members change to the Rejected state, P changes to the Rejected state.

Promise.any = function (promises) { return new Promise((resolve, reject) => { let count = 0; for (let i = 0; i < promises.length; i++) { if (! (promises[i] instanceof Promise)) { promises[i] = Promise.resolve(promises[i]); } promises[i].then( (res) => { resolve(res); }, () => { count++; If (count === promises. Length) {// The error thrown by this method is an AggregateError instance. // It is an array with each member corresponding to an error thrown by the Rejected operation. reject(new AggregateError([], "All promises were rejected")); }}); }}); };Copy the code
  • Promise.allSettled()

The method takes a set of Promise instances as parameters (ARR), wrapped into a new Promise instance (p). Only when all members of ARR return the result, no matter pity or Rejected, P will end. This method returns a new Promise instance. Once it is fulfilled, the state is always fulfilled and will not become Rejected.

Promise.allSettled = function (promises) {
    return new Promise(async (resolve) => {
      let result = [];
      for (let i = 0; i < promises.length; i++) {
        if (promises[i] instanceof Promise) {
            try {
                const res = await promises[i]
                result[i] = {
                    status: 'Fulfilled',
                    value: res,
                  };
            } catch (reason) {
                result[i] = {
                    status: 'Rejected',
                    reason,
                  };
            }
        } else {
          result[i] = {
            status: 'Fulfilled',
            value: promises[i],
          };
        }
      }
      resolve(result);
    });
  };
Copy the code

At this point, we have completed the Promise of the A+ specification and the implementation of all the instance methods and static methods in ES6. If you feel helpful, welcome to support 😀. Reference: es6.ruanyifeng.com/#docs/promi…