lewenweijia / notes

🏊 dive dive diving
1 stars 0 forks source link

(占坑) 简易实现: Promise #16

Open lewenweijia opened 5 years ago

lewenweijia commented 5 years ago
function Promise{
  constructor(executor) {
    this.promiseChain = [];

    try {
      executor(this.onResolve, this.onReject);
    } catch(err) {
      this.onRject(err);
    }
  }

  then(onResolve) {
    this.promiseChain.push(onResolve);

    return this;
  }

  onResolve(value) {
    try {
      this.promiseChain.reduce((a, b) => val => b(a(val)))(value);      
    } catch (err) {
      this.onReject(err);
    }
  }
}
lewenweijia commented 5 years ago
class Promise {
  status = "pending";
  value = null;
  handlers = [];

  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (err) {
      this.reject(err);
    }
  }

  resolve = res => {
    this.status = "fulfilled";
    this.value = res;
    this.handlers.forEach(this._handle);
  };

  reject = err => {
    this.status = "rejected";
    this.value = err;
    this.handlers.forEach(this._handle);
  };

  _handle = handler => {
    switch (this.status) {
      case "pending":
        this.handlers.push(handler);
        break;
      case "fulfilled":
        handler.onFullfilled(this.value);
        break;
      case "rejected":
        handler.onReject(this.value);
        break;
    }
  };

  then = (onFullfilled, onReject) => {
    return new Promise((resolve, reject) => {
      this._handle.push({
        onFullfilled: value => void resolve(onFullfilled(value)),
        onReject: err => void reject(onReject(err))
      });
    });
  };
}