Promise.all,Promise.race,Promise.finally实现

Promise.finally

Promise.prototype.finally = function(cb) {
        const P = this.constructor;
        return this.then(
          val => P.resolve(cb()).then(() => val),
          err =>
            P.resolve(cb()).then(() => {
              throw err;
            })
        );
      };

Promise.all

function promiseAll(promises) {
        return new Promise((resolve, reject) => {
          if (!Array.isArray(promises)) {
            return reject(new TypeError("argument must be anarray"));
          }
          const countNum = 0;
          const promiseNum = promises.length;
          const resultVal = new Array(promiseNum);
          for (let i = 0; i < promiseNum; i++) {
            Promise.resolve(promises[i]).then(
              val => {
                countNum++;
                resultVal[i] = val;
                if (countNum === promiseNum) {
                  return resolve(resultVal);
                }
              },
              err => {
                return reject(err);
              }
            );
          }
        });
      }

Promise.race

function race(promises) {
        return new Promise((resolve, reject) => {
          promises.forEach(element => {
            Promise.resolve(element).then(resolve, reject);
          });
        });
      }

你可能感兴趣的:(Promise.all,Promise.race,Promise.finally实现)