20.自定义封装-指定多个回调任务

异步的时候指定多个回调函数,比如下面这样

  let p = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("ok");
    }, 1000);
  });
  p.then(
    (value) => {
      console.log(value);
    },
    (reason) => {
      console.log(reason);
    }
  );
  p.then(
    (value) => {
      alert(value);
    },
    (reason) => {
      alert(reason);
    }
  );

此时只会执行最后一个回调,也就是 alert

因为两个 p.then 都走了 PromiseState === "pending" 这个判断,第一个 p.then 把 callback 赋值了以后, 第二个 p.then 也给 callback 赋值了,就直接把 callback 给覆盖了,所以就只执行了最后一个回调

所以我们需要把这些回调都保存起来而不是只保存一个,所以 callback 改为 callbacks 变成一个数组

  function Promise(executor) {
    this.PromiseState = "pending";
    this.PromiseResult = null;
    this.callbacks = [];
    function resolve(data) {
      if (self.PromiseState !== "pending") return;
      self.PromiseState = "resolved";
      self.PromiseResult = data;
      if (self.callback.onResolved) {
        self.callback.onResolved(self.PromiseResult);
      }
    }
    function reject(data) {
      if (self.PromiseState !== "pending") return;
      self.PromiseState = "rejected";
      self.PromiseResult = data;
      if (self.callback.onRejected) {
        self.callback.onRejected(self.PromiseResult);
      }
    }
    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }

 然后 then 方法里面 直接 push

  Promise.prototype.then = function (onResolved, onRejected) {
    if (this.PromiseState === "resolved") {
      onResolved(this.PromiseResult);
    }
    if (this.PromiseState === "rejected") {
      onRejected(this.PromiseResult);
    }
    if (this.PromiseState === "pending") {
      this.callbacks.push({
        onResolved,
        onRejected,
      });
    }
  };

 所以 Promise 里面执行完 resolve() 或者 reject() 以后的代码也得改变

  function Promise(executor) {
    this.PromiseState = "pending";
    this.PromiseResult = null;
    this.callbacks = [];
    function resolve(data) {
      if (self.PromiseState !== "pending") return;
      self.PromiseState = "resolved";
      self.PromiseResult = data;
      self.callbacks.forEach((item) => {
        item.onResolved(self.PromiseResult);
      });
    }
    function reject(data) {
      if (self.PromiseState !== "pending") return;
      self.PromiseState = "rejected";
      self.PromiseResult = data;
      self.callbacks.forEach((item) => {
        item.onRejected(self.PromiseResult);
      });
    }
    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值