简单实现Promise

简单实现手写js中的promise

class MyPromise {
  constructor(fn) {
    this.state = "pending";
    this.value = null;
    this.resolve = this.resolve.bind(this);
    this.reject = this.reject.bind(this);
    this.resolveStack = [];
    this.rejectStack = [];
    // 创建时立马执行
    fn(this.resolve, this.reject);
  }

  static all(li) {
    return new MyPromise((rs, rj) => {
      if (!Array.isArray(li)) {
        return rj("not array");
      }

      const results = [];
      let completes = 0;

      li.forEach((_promise, idx) => {
        _promise.then((res) => {
          results[idx] = res;
          completes++;
          if (completes === li.length) {
            rs(results);
          }
        });
      });
    });
  }

  resolve(value) {
    this.value = value;
    this.state = "fulfilled";
    while (this.resolveStack.length) {
      this.value = this.resolveStack.shift()(this.value);
    }
  }

  reject(value) {
    this.state = "rejected";
    this.value = value;
  }

  then(onFulfilled, onRejected) {
    this.resolveStack.push(onFulfilled);
    this.rejectStack.push(onRejected);
    return this;
  }
}

测试一下试试

new MyPromise((rs, rj) => {
  setTimeout(() => {
    rs(1);
  }, 1000);
})
  .then((val) => {
    console.log("running ", val);
    return val + 1;
  })
  .then((val) => {
    console.log("running ", val);
    return val + 1;
  });

const returnPro = (num) => {
  return new MyPromise((rs, rj) => {
    setTimeout(() => {
      console.log("returnPro running", num);
      rs(num);
    }, 1000 * num);
  });
};

MyPromise.all([returnPro(1), returnPro(2), returnPro(3)]).then((res) => {
  console.log(res);
});

结果问题不大
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值