手写Promise

这篇文章展示了如何从头构建一个简单的Promise类——MyPromise。它包括了Promise的三种状态(pending,fulfilled,rejected)、解决(resolve)和拒绝(reject)方法,以及then方法来处理回调。此外,还提供了静态方法如resolve、reject和all来处理多个Promise实例。
摘要由CSDN通过智能技术生成

直接上代码

class MyPromise {
  #state = "pending";
  #callbacks = [];
  #result = undefined;
  constructor(executor) {
    try {
      executor(this.#resolve.bind(this), this.#reject.bind(this));
    } catch (err) {
      this.#reject(err);
    }
  }
  #resolve(result) {
    this.#state = "fulfilled";
    this.#result = result;
    for (const callback of this.#callbacks) {
      callback.onfulfilled(this.#result);
    }
  }
  #reject(reason) {
    this.#state = "rejected";
    this.#result = reason;
    for (const callback of this.#callbacks) {
      callback.onrejected(this.#result);
    }
  }
  then(onfulfilled, onrejected) {
    return new MyPromise((resolve, reject) => {
      if (this.#state === "fulfilled") {
        if (typeof onfulfilled === "function") {
          const result = onfulfilled(this.#result);
          if (result instanceof MyPromise) {
            result.then(
              (res) => {
                resolve(res);
              },
              (err) => {
                reject(err);
              }
            );
          } else {
            resolve(result);
          }
        } else {
          resolve(this.#result);
        }
      }
      if (this.#state === "rejected") {
        if (typeof onrejected === "function") {
          const result = onrejected(this.#result);
          if (result instanceof MyPromise) {
            result.then(
              (res) => {
                resolve(res);
              },
              (err) => {
                reject(err);
              }
            );
          } else {
            resolve(result);
          }
        } else {
          reject(this.#result);
        }
      }
      if (this.#state === "pending") {
        this.#callbacks.push({
          onfulfilled: () => {
            if (typeof onfulfilled === "function") {
              const result = onfulfilled(this.#result);
              if (result instanceof MyPromise) {
                result.then(
                  (res) => {
                    resolve(res);
                  },
                  (err) => {
                    reject(err);
                  }
                );
              } else {
                resolve(result);
              }
            } else {
              resolve(this.#result);
            }
          },
          onrejected: () => {
            if (typeof onrejected === "function") {
              const result = onrejected(this.#result);
              if (result instanceof MyPromise) {
                result.then(
                  (res) => {
                    resolve(res);
                  },
                  (err) => {
                    reject(err);
                  }
                );
              } else {
                resolve(result);
              }
            } else {
              reject(this.#result);
            }
          },
        });
      }
    });
  }
  catch(onrejected) {
    this.then(undefined, onrejected);
  }
  static resolve(data) {
    return new MyPromise((resolve, reject) => {
      if (data instanceof MyPromise) {
        data.then(
          (res) => {
            resolve(res);
          },
          (err) => {
            reject(err);
          }
        );
      } else {
        resolve(data);
      }
    });
  }
  static reject(data) {
    return new MyPromise((resolve, reject) => {
      reject(data);
    });
  }
  static all(promises) {
    return new MyPromise((resolve, reject) => {
      let count = 0;
      let fulfilledCount = 0;
      let resultList = [];
      for (const promise of promises) {
        let index = count;
        promise.then(
          (res) => {
            resultList[index] = res;
            fulfilledCount++;
            if (fulfilledCount === count) {
              resolve(resultList);
            }
          },
          (err) => {
            reject(err);
          }
        );
        count++;
      }
      if (count === 0) {
        resolve([]);
      }
    });
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张太难

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值