简版Promise

33 阅读1分钟
class minePromise {

  static PADDING = 'padding';
  static SUCCESS = 'success'; // 成功
  static FAIL = 'fail';

  constructor(fn){
    this.PromiseState = minePromise.PADDING;
    this.PromiseResult = null;
    this.SuccessList = [];
    this.FailList = [];
    fn(this.resole.bind(this),this.reject.bind(this))
  };

  resole(res) {
    if(this.PromiseState===minePromise.PADDING) {
      this.PromiseState = minePromise.SUCCESS;
      this.PromiseResult = res;
      this.SuccessList.forEach(item=>{
        setTimeout(()=>{
          item(this.PromiseResult)
        });
      })
    }
  };

  reject(res) {
    if(this.PromiseState===minePromise.PADDING) {
      this.PromiseState=minePromise.FAIL;
      this.PromiseResult = res;
      this.FailList.forEach(item=>{
        setTimeout(()=>{
          item(this.PromiseResult)
        });
      })
    }
  };

  then(successBack,failBack) {
    if(this.PromiseState===minePromise.SUCCESS) {
      setTimeout(()=>{
        successBack(this.PromiseResult)
      });
    } else if (this.PromiseState===minePromise.FAIL) {
      setTimeout(()=>{
        failBack(this.PromiseResult)
      });
    } else {
      this.SuccessList.push(successBack);
      this.FailList.push(failBack);
    }
  }
}