From the morning liver to the evening, the results of the promise chain call has not been studied, I tm good food!!

all

Method is used to wrap multiple Promise instances into a new Promise instance.

The arguments must have an Iterator interface and each member returned is a Promise instance.

This method will gradually change the state to pity only after all the incoming promise instances are resolved. As long as one promise instance is rejected, it will be rejected, and then the first rejected instance will be returned.

race

Method is used to wrap multiple Promise instances into a new Promise instance.

If one of the incoming promise instances changes state, the promise.race state changes. This is like a race, where the state of the first promise instance changes and the promise.race instance changes.

This method controls the load duration of the network, and changes its status to Rejected if the network load is not completed

const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() = > reject(new Error('request timeout')), 5000)})]); p .then(console.log)
.catch(console.error);
Copy the code

allSettled

Used to determine whether a set of asynchronous operations have all ended (whether successful or unsuccessful).

This will be a pity once the state changes, and it will not become rejected.

The parameters received by the then method correspond to the order in which the Promise instance is passed in. Are the parameters passed in by the instance of promise that changes the state.

  • Someday: {status: ‘depressing’, value: the parameters that will be passed during success}
  • {status: ‘rejected’, reason: parameter passed in the failed}

any

Method is used to wrap multiple Promise instances into a new Promise instance.

This method corresponds to the all method.

As long as one parameter instance becomes a depressing state, the packaging instance will become a depressing state. If all parameter instances become the Rejected state, the wrapper instance becomes the Rejected state.

Handwritten code

    /** * Promise accepts an executor function. This function accepts two arguments * * all: If all the promise states passed in become fulfilled, the array of the resolve parameters will be returned. If one of the promise states passed in becomes Fulfilled, the reason parameter will be returned. * * Race: Promises will be made by whoever changes the state first. * * allSettled: Promises, if the state changes, whether this is a big pity or Rejected, will directly change the state of promise. * * /
    class MyPromise {
      constructor(executor) {
        let resolve = (value) = > {
          // This is a big pity. Only when the state is pending can the state be changed, which will be fulfilled
          if (this.status === 'pending') {
            this.status = 'fulfilled'
            this.value = value
            // When resolve is executed asynchronously, we execute functions in the event array
            this.fulfilledArr.forEach(fn= >{ fn && fn() }); }}let reject = (reason) = > {
          // Only when the state is pending can you change it to Rejected
          if (this.status === 'pending') {
            this.status = 'rejected'

            this.reason = reason
            // console.log(" current reason value ", this.reason, reason)
            // When rejected is executed asynchronously, we execute the function in the event array
            this.rejectedArr.forEach(fn= >{ fn && fn() }); }}// Define a state variable
        this.status = 'pending';
        // Define a parameter that will be passed during the depressing state
        this.value = null;
        // Define a parameter passed in the Rejected state
        this.reason = null;
        // Array of successful events
        this.fulfilledArr = []
        this.rejectedArr = []
        try {
          executor(resolve, reject)
        } catch (error) {
          reject(error)
        }
      }

      // static all(promises) {
      // let successArr = [];
      // for (let i = 0; i < promises.length; i++) {
      // if (promises[i].status === 'rejected') {
      // return new MyPromise((resolve, reject) => {
      / / / / the console. The log (" = = = = = = = calls ", promises [I]. "reason, I)
      // reject(promises[i].reason)
      / /})
      / /}

      // if (promises[i].status === 'fulfilled') {
      / / the console. The log (" = = = = = = = calls the ", promises [I] value, I)
      // successArr.push(promises[i].then(res => {
      // successArr.push(res)
      / /}))
      / /}
      / /}
      // if (successArr.length === promises.length) {
      // return new MyPromise((resolve, reject) => {
      // try {
      // resolve(successArr)
      // } catch (error) {
      // reject(error)
      / /}
      / /})
      / /}

      // }

      static all(promises) {
        let arr = [];
        let count = 0;
        return new MyPromise((resolve, reject) = > {
          for (let i = 0; i < promises.length; i++) {
            promises[i].then(data= > {
              arr[i] = data;
              count++;
              // If all the states are fulfilled, then the parameters passed in asynchronously will be returned as an array.
              if (count == promises.length) {
                resolve(arr);
              };
              // If a promise fails, it passes arguments to reject. The reject is the internally implemented function.
            }, (err) = > {
              reject(err)
            });
          };
        });
      }

      / / race method

      static race(promises) {
        return new MyPromise((resolve, reject) = > {
          for (let i = 0; i < promises.length; i++) {
            // Because the loop executes instantaneously
            promises[i].then(resolve, reject)
          }
        })
      }

      // The any method implements the exact opposite of the all method
      static any(promises) {
        let rejectArr = [];

        return new MyPromise((resolve, reject) = > {
          for (let i = 0; i < promises.length; i++) {
            promises[i].then((res) = > {
              resolve(res)
            }, (err) = > {
              rejectArr.push(err);
              if (promises.length === rejectArr.length) {
                reject(rejectArr)
              }
            })
          }
        })
      }

      / / allSettled method
      static allSettled(promises) {
        let arr = []
        return new Promise((resolve, reject) = > {
          // He will change as soon as all the states change.
          for (let i = 0; i < promises.length; i++) {
            promises[i].then(res= > {
              arr.push({
                status: 'fulfilled'.value: res
              })
              // This is a big pity
              if (arr.length === promises.length) {
                resolve(arr)
              }
            }, (err) = > {
              arr.push({
                status: 'rejected'.reason: err
              })
              // This is a big pity
              if (arr.length === promises.length) {
                resolve(arr)
              }
            })

          }
        })
      }
      
      / / resolve method
      static resolve(params) {
        return new MyPromise((resolve) = > {
          resolve(params)
        })
      }

      / / reject method
      static reject(params) {
        return new MyPromise((resolve, reject) = > {
          reject(params)
        })
      }
      
      / / catch method
      catch(onFail) {
        return this.then(null, onFail)
      }

      // Define the then method
      then(onSuccess, onFail) {
        let x;
        return new Promise((resolve, reject) = > {
          // Determine the state and let the corresponding state function execute.
          if (this.status === 'fulfilled') {
            try {
              // pass down the resolve, reject arguments when no callback function in then is provided
              onSuccess = typeof onSuccess === 'function' ? onSuccess : v= > v;
              x = onSuccess(this.value)
              resolve(x)
            } catch (err) {
              reject(err)
            }
          }
          if (this.status === 'rejected') {
            try {
              // pass down the resolve, reject arguments when no callback function in then is provided
              onFail = typeof onFail === 'function' ? onFail : v= > v;
              x = onFail(this.reason)
              resolve(x)
            } catch (err) {
              reject(err)
            }
          }
          // When the state is pending, the events are placed in the corresponding event array
          if (this.status === 'pending') {
            // this.fulfilledArr.push(
            // onSuccess)
            // this.rejectedArr.push(
            // onFail)
            this.fulfilledArr.push(() = > {
              try {
                // pass down the resolve, reject arguments when no callback function in then is provided
                onSuccess = typeof onSuccess === 'function' ? onSuccess : v= > v;
                x = onSuccess(this.value)
                resolve(x)
              } catch (err) {
                reject(err)
              }
            })
            this.rejectedArr.push(() = > {
              try {
                // pass down the resolve, reject arguments when no callback function in then is provided
                onFail = typeof onFail === 'function' ? onFail : v= > v;
                x = onFail(this.reason)
                resolve(x)
              } catch (err) {
                reject(err)
              }
            })
          }
        })
      }
    }
Copy the code