手写 Promise 静态方法

时间:2021-09-10 01:13:36

手写 promise

前置背景:大白话手写 promise

resolve、reject

作为类直接调用的方法,自然是静态方法。
**resolve 与 reject 的原理都是内部自己实例化了一个 promise,然后去调用 resolve 或 reject。**本质和自己实例化 promise 调用没啥区别。

class LcPromise {
  constructor(executed) {}
  then(onFulfilled, onRejected) {}
	catch(onRejected) {}
  finally(fn) {}

  static resolve(value) {
    return new LcPromise((resolve, reject) => resolve(value))
  }

  static reject(reason) {
    return new LcPromise((resolve, reject) => reject(reason))
  }
}

all、allSettled

all 方法的用法:接收一个 promise 实例数组,等待数组中所有的 promise fulfilled 后将调用 then 的 onFulfilled,只要其中有一个promise rejected,就立即调用 then 的 onRejected。

Promise.all([]).then(onFulfilled).catch(onRejected)

由此可知 all 肯定返回一个 promise 实例,要不然咋调用 then。我们可以一个一个等待数组中 promise 实例的结果,当 promise 实例全部执行的是 onFulfilled,那就说明整个 all 已经是 fulfilled 状态,resolve all 返回的 promise 实例。如果其中一个执行 onRejected,则说明 all 中出现错误,整个 all 的 promise 实例就可以 reject 了。
整个问题的关键就在于 all 返回的 promise 什么时候执行 resolve,什么时候执行 reject。

static all(promiseArr) {
  const allResult = [];
  return new LcPromise((resolve, reject) => {
    promiseArr.forEach((promise) => {
      // 执行每个 promise 实例
      promise.then(
        (res) => {
          // 收集每个 promise 的成功结果
          allResult.push(res);
          // 当收集完所有的 promise,说明整体的 promise 应该为 fulfilled 状态了,执行 resolve
          if (allResult.length === promiseArr.length) resolve(allResult);
        },
        (err) => {
          // 只要有一个 promise rejected 了,就执行整个 promise 的 reject 函数
          reject(err);
        }
      );
    });
  });
}

allSettled 与 all 差不多,区别就是当 allSettled 接收的 promise 数组中存在 reject 的 promise 时,它不会中断整个 allSettled 函数的执行,allSettled 返回的 promise 不会变成 rejected,依然为 pending,继续执行数组中后续的 promise。说明 allSettled 返回的 promise 不会执行 reject 函数,它最后一定是 fulfilled 状态。对于数组中 rejected 状态的 promise,allSettled 的返回值是一个数组对象。对象中包含了每个 promise 的状态和结果或错误信息。

static allSettled(promiseArr) {
  const allResult = [];
  return new LcPromise((resolve, reject) => {
    promiseArr.forEach((promise) => {
      promise.then(
        (res) => {
          allResult.push({ status: "fulfilled", res: res });
          if (allResult.length === promiseArr.length) resolve(allResult);
        },
        (err) => {
          allResult.push({ status: "rejected", err: err });
          if (allResult.length === promiseArr.length) resolve(allResult);
        }
      );
    });
  });
}

测试:

const p1 = new LcPromise((resolve, reject) => {
  resolve(1111);
});
const p2 = new LcPromise((resolve, reject) => {
  // resolve(2222);
  reject("hhh");
});
const p3 = new LcPromise((resolve, reject) => {
  resolve(3333);
});

LcPromise.all([p1, p2, p3])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

// hhh

LcPromise.allSettled([p1, p2, p3])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

// [
//   { status: 'fulfilled', res: 1111 },
//   { status: 'rejected', err: 'hhh' },
//   { status: 'fulfilled', res: 3333 }
// ]

race、any

race 方法的用法:基本也和 all 差不多,区别就是只要数组中有一个 promise 确定了状态就立即确定了整个 race 返回的 promise 的状态。
所以有一个 promise 执行了 then 方法,就可以立即执行整体 promise 的 resolve 方法或 reject 方法。

static race(promiseArr) {
  return new LcPromise((resolve, reject) => {
    promiseArr.forEach((promise) => {
      // 有一个 promise 确定了状态,就立即确定了整体 promise 的状态
      promise.then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
    })
  })
}

any 的用法是,只要数组中有一个 promise 为 fulfilled 就执行 resolve,整体 promise 为 fulfilled。当数组中所有 promise 为 rejected 才执行 reject 函数,整体为 rejected,并且返回一个包含所有错误信息的合并错误数组new AggregateError(arr)
注意这个构造函数 nodejs 没有实现,只能在浏览器中测试。它有一个 errors 属性,可以查看错误信息。

static any(promiseArr) {
  return new LcPromise((resolve, reject) => {
    const reasonArr = []
    promiseArr.forEach((promise) => {
      promise.then(res => {
        resolve(res)
      }, err => {
        reasonArr.push(err)
        if (promiseArr.length === reasonArr.length) reject(new AggregateError(reasonArr))
      })
    })
  })
}

测试:

const p1 = new LcPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(1111);
  }, 3000);
});
const p2 = new LcPromise((resolve, reject) => {
  // resolve(2222);
  setTimeout(() => {
    reject("hhh");
  }, 1000);
});
const p3 = new LcPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(3333);
  }, 2000);
});

LcPromise.race([p1, p2, p3])
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

// hhh 打印最快确定状态的信息
// 所有 promise rejected 的情况
const p1 = new LcPromise((resolve, reject) => {
  setTimeout(() => {
    // resolve(1111);
    reject("h1");
  }, 3000);
});
const p2 = new LcPromise((resolve, reject) => {
  // resolve(2222);
  setTimeout(() => {
    reject("h2");
  }, 1000);
});
const p3 = new LcPromise((resolve, reject) => {
  setTimeout(() => {
    // resolve(3333);
    reject("h3");
  }, 2000);
});

LcPromise.any([p1, p2, p3])
  .then((res) => console.log(res))
  .catch((err) => console.log(err.errors));

// (3) ['h2', 'h3', 'h1']

完整的 promise

const PROMISE_STATUS_PENDING = "pending";
const PROMISE_STATUS_FULFILLED = "fulfilled";
const PROMISE_STATUS_REJECTED = "rejected";

const execFunctionWithCatchError = (execFn, value, resolve, reject) => {
  try {
    const res = execFn(value);
    resolve(res);
  } catch (error) {
    reject(error);
  }
};

class LcPromise {
  constructor(executed) {
    this.status = PROMISE_STATUS_PENDING;

    this.value = undefined;
    this.reason = undefined;

    this.onFulfilledFns = [];
    this.onRejectedFns = [];

    const resolve = (value) => {
      this.value = value;
      queueMicrotask(() => {
        if (this.status != PROMISE_STATUS_PENDING) return;
        this.status = PROMISE_STATUS_FULFILLED;
        this.onFulfilledFns.forEach((fns) => fns(this.value));
      });
    };
    const reject = (reason) => {
      this.reason = reason;
      queueMicrotask(() => {
        if (this.status != PROMISE_STATUS_PENDING) return;
        this.status = PROMISE_STATUS_REJECTED;
        this.onRejectedFns.forEach((fns) => fns(this.reason));
      });
    };

    executed(resolve, reject);
  }

  then(onFulfilled, onRejected) {
    onFulfilled = onFulfilled || ((value) => value);
    onRejected =
      onRejected ||
      ((err) => {
        throw err;
      });

    return new LcPromise((resolve, reject) => {
      // 在 resolve reject 中执行
      if (onFulfilled)
        this.onFulfilledFns.push(() => {
          execFunctionWithCatchError(onFulfilled, this.value, resolve, reject);
        });
      if (onRejected)
        this.onRejectedFns.push(() => {
          execFunctionWithCatchError(onRejected, this.reason, resolve, reject);
        });

      // 在自身中执行
      if (this.status === PROMISE_STATUS_FULFILLED) {
        execFunctionWithCatchError(onFulfilled, this.value, resolve, reject);
      }
      if (this.status === PROMISE_STATUS_REJECTED) {
        execFunctionWithCatchError(onRejected, this.reason, resolve, reject);
      }
    });
  }

  catch(onRejected) {
    return this.then(undefined, onRejected);
  }

  finally(fn) {
    this.then(fn, fn);
  }

  static resolve(value) {
    return new LcPromise((resolve, reject) => resolve(value));
  }

  static reject(reason) {
    return new LcPromise((resolve, reject) => reject(reason));
  }

  static all(promiseArr) {
    const allResult = [];
    return new LcPromise((resolve, reject) => {
      promiseArr.forEach((promise) => {
        // 执行每个 promise 实例
        promise.then(
          (res) => {
            // 收集每个 promise 的成功结果
            allResult.push(res);
            // 当收集完所有的 promise,说明整体的 promise 应该为 fulfilled 状态了,执行 resolve
            if (allResult.length === promiseArr.length) resolve(allResult);
          },
          (err) => {
            // 只要有一个 promise rejected 了,就执行整个 promise 的 reject 函数
            reject(err);
          }
        );
      });
    });
  }

  static allSettled(promiseArr) {
    const allResult = [];
    return new LcPromise((resolve, reject) => {
      promiseArr.forEach((promise) => {
        promise.then(
          (res) => {
            allResult.push({ status: "fulfilled", res: res });
            if (allResult.length === promiseArr.length) resolve(allResult);
          },
          (err) => {
            allResult.push({ status: "rejected", err: err });
            if (allResult.length === promiseArr.length) resolve(allResult);
          }
        );
      });
    });
  }

  static race(promiseArr) {
    return new LcPromise((resolve, reject) => {
      promiseArr.forEach((promise) => {
        promise.then(
          (res) => {
            resolve(res);
          },
          (err) => {
            reject(err);
          }
        );
      });
    });
  }

  static any(promiseArr) {
    return new LcPromise((resolve, reject) => {
      const reasonArr = [];
      promiseArr.forEach((promise) => {
        promise.then(
          (res) => {
            resolve(res);
          },
          (err) => {
            reasonArr.push(err);
            if (promiseArr.length === reasonArr.length)
              reject(new AggregateError(reasonArr));
          }
        );
      });
    });
  }
}