30.自定义封装Promise-class版本的实现

1.先创建 class 结构

  class Promise {}

2.声明构造方法,把原本的 Promise 函数代码放进去

  class Promise {
    // 构造方法
    constructor(executor) {
      const self = this;

      this.PromiseState = "pending";
      this.PromiseResult = null;
      this.callbacks = [];

      function resolve(data) {
        if (self.PromiseState !== "pending") return;
        self.PromiseState = "resolved";
        self.PromiseResult = data;
        setTimeout(() => {
          self.callbacks.forEach((item) => {
            item.onResolved(self.PromiseResult);
          });
        });
      }
      function reject(data) {
        if (self.PromiseState !== "pending") return;
        self.PromiseState = "rejected";
        self.PromiseResult = data;
        setTimeout(() => {
          self.callbacks.forEach((item) => {
            item.onRejected(self.PromiseResult);
          });
        });
      }

      try {
        executor(resolve, reject);
      } catch (e) {
        reject(e);
      }
    }
  }

3.声明then方法,把原本的then方法的代码放进去

  class Promise {
    // 构造方法
    constructor(executor) {
      const self = this;

      this.PromiseState = "pending";
      this.PromiseResult = null;
      this.callbacks = [];

      function resolve(data) {
        if (self.PromiseState !== "pending") return;
        self.PromiseState = "resolved";
        self.PromiseResult = data;
        setTimeout(() => {
          self.callbacks.forEach((item) => {
            item.onResolved(self.PromiseResult);
          });
        });
      }
      function reject(data) {
        if (self.PromiseState !== "pending") return;
        self.PromiseState = "rejected";
        self.PromiseResult = data;
        setTimeout(() => {
          self.callbacks.forEach((item) => {
            item.onRejected(self.PromiseResult);
          });
        });
      }

      try {
        executor(resolve, reject);
      } catch (e) {
        reject(e);
      }
    }

    // then方法
    then(onResolved, onRejected) {
      const self = this;
      if (typeof onRejected !== "function") {
        onRejected = (reason) => {
          throw reason;
        };
      }
      if (typeof onResolved !== "function") {
        onResolved = (value) => value;
      }
      return new Promise((resolve, reject) => {
        function callback(type) {
          try {
            let result = type(self.PromiseResult);
            if (result instanceof Promise) {
              result.then(
                (v) => {
                  resolve(v);
                },
                (r) => {
                  reject(r);
                }
              );
            } else {
              resolve(result);
            }
          } catch (e) {
            reject(e);
          }
        }
        if (this.PromiseState === "resolved") {
          setTimeout(() => {
            callback(onResolved);
          });
        }
        if (this.PromiseState === "rejected") {
          setTimeout(() => {
            callback(onRejected);
          });
        }
        if (this.PromiseState === "pending") {
          this.callbacks.push({
            onResolved: function () {
              callback(onResolved);
            },
            onRejected: function () {
              callback(onRejected);
            },
          });
        }
      });
    }
  }

4.catch方法也是一样

class Promise {
  // 构造方法
  constructor(executor) {
    const self = this

    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = [];

    function resolve(data) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'resolved'
      self.PromiseResult = data
      setTimeout(() => {
        self.callbacks.forEach((item) => {
          item.onResolved(self.PromiseResult);
        });
      })
    }
    function reject(data) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'rejected'
      self.PromiseResult = data
      setTimeout(() => {
        self.callbacks.forEach((item) => {
          item.onRejected(self.PromiseResult);

        });
      })
    }

    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e)
    }
  }

  // then方法
  then(onResolved, onRejected) {
    const self = this;
    if (typeof onRejected !== 'function') {
      onRejected = reason => {
        throw reason
      }
    }
    if (typeof onResolved !== 'function') {
      onResolved = value => value
    }
    return new Promise((resolve, reject) => {
      function callback(type) {
        try {
          let result = type(self.PromiseResult);
          if (result instanceof Promise) {
            result.then(
              (v) => {
                resolve(v);
              },
              (r) => {
                reject(r);
              }
            );
          } else {
            resolve(result);
          }
        } catch (e) {
          reject(e);
        }
      }
      if (this.PromiseState === "resolved") {
        setTimeout(() => {
          callback(onResolved);
        })
      }
      if (this.PromiseState === "rejected") {
        setTimeout(() => {
          callback(onRejected);
        })
      }
      if (this.PromiseState === "pending") {
        this.callbacks.push({
          onResolved: function () {
            callback(onResolved);
          },
          onRejected: function () {
            callback(onRejected);
          },
        });
      }
    });
  }

  // catch方法
  catch(onRejected) {
    return this.then(undefined, onRejected)
  }
}

5.resolve 方法不太一样,它是 Promise 的方法,所以前面加上 static 进行描述,表明是一个静态成员,reject、all、race 也是如此

class Promise {
  // 构造方法
  constructor(executor) {
    const self = this

    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = [];

    function resolve(data) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'resolved'
      self.PromiseResult = data
      setTimeout(() => {
        self.callbacks.forEach((item) => {
          item.onResolved(self.PromiseResult);
        });
      })
    }
    function reject(data) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'rejected'
      self.PromiseResult = data
      setTimeout(() => {
        self.callbacks.forEach((item) => {
          item.onRejected(self.PromiseResult);

        });
      })
    }

    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e)
    }
  }

  // then方法
  then(onResolved, onRejected) {
    const self = this;
    if (typeof onRejected !== 'function') {
      onRejected = reason => {
        throw reason
      }
    }
    if (typeof onResolved !== 'function') {
      onResolved = value => value
    }
    return new Promise((resolve, reject) => {
      function callback(type) {
        try {
          let result = type(self.PromiseResult);
          if (result instanceof Promise) {
            result.then(
              (v) => {
                resolve(v);
              },
              (r) => {
                reject(r);
              }
            );
          } else {
            resolve(result);
          }
        } catch (e) {
          reject(e);
        }
      }
      if (this.PromiseState === "resolved") {
        setTimeout(() => {
          callback(onResolved);
        })
      }
      if (this.PromiseState === "rejected") {
        setTimeout(() => {
          callback(onRejected);
        })
      }
      if (this.PromiseState === "pending") {
        this.callbacks.push({
          onResolved: function () {
            callback(onResolved);
          },
          onRejected: function () {
            callback(onRejected);
          },
        });
      }
    });
  }

  // catch方法
  catch(onRejected) {
    return this.then(undefined, onRejected)
  }

  // resolve方法
  static resolve(value) {
    return new Promise((resolve, reject) => {
      if (value instanceof Promise) {
        value.then(v => {
          resolve(v)
        }, r => {
          reject(r)
        })
      } else {
        resolve(value)
      }
    })
  }

  // reject方法
  static resolve(reason) {
    return new Promise((resolve, reject) => {
      reject(reason)
    })
  }

  // all方法
  static all(promises) {
    return new Promise((resolve, reject) => {
      let count = 0
      let arr = []
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(v => {
          count++
          arr[i] = v
          if (count === promises.length) {
            resolve(arr)
          }
        }, r => {
          reject(r)
        })
      }
    })
  }

  // race方法
  static race(promises) {
    return new Promise((resolve, reject) => {
      for (let i = 0; i < promises.length; i++) {
        promises[i].then(v => {
          resolve(v)
        }, r => {
          reject(r)
        })
      }
    })
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值