封装一个promise类

class HD {
   static PENDING = "pending";
   static FULFILLED = "fulfilled";
   static REJECTED = "rejected";
   constructor(executor) {
      this.status = HD.PENDING;
      this.value = null;
      this.callbacks = [];
      try {
         executor(this.resolve.bind(this), this.reject.bind(this));
      } catch (error) {
         this.reject(error);
      }
   }
   resolve(value){
      if(this.status == HD.PENDING) {
         this.status = HD.FULFILLED;
         this.value = value;
         setTimeout(() => {
            this.callbacks.map(callback => {
               callback.onFulfilled(value);
            });
         });
      }
   }
   reject(value){
      if(this.status == HD.PENDING){
         this.status = HD.REJECTED;
         this.value = value;
         setTimeout(() => {
            this.callbacks.map(callback => {
               callback.onRejected(value);
            })
         })
      }
   }
   
   then(onFulfilled, onRejected){
      if(typeof onFulfilled != "function"){
         onFulfilled = value => value;
      }
      if(typeof onRejected != "function"){
         onRejected = value => value;
      }
     return new HD((resolve, reject) => {
        if(this.status == HD.FULFILLED){
         setTimeout(() => {
            try {
               let result = onFulfilled(this.value);
               if(result instanceof HD){
                  result.then(resolve, reject);
               } else {
                  resolve(result);
               }
            } catch (error) {
               //onRejected(error);
               reject(error);
            }
         })
      }
      if(this.staus == HD.REJECTED) {
         setTimeout(() => {
            try(
              let result = onRejected(this.value);
              if (result instanceof HD){
                 result.then(resolve, reject);
              } else {
                 resolve(result);
              }
            ) catch (error) {
               //onRejected(error)
               reject(error);
            }
         })
      }
      if(this.status == HD.PENDING) {
         this.callbacks.push({
           onFulfilled: value => {
              try {
                 onFulfilled(value);
              } catch (error) {
                 onRejected(error);
              }
           },
           onRejected: value => {
              try { 
                onRejected(value);
              } catch (error) {
                onRejected(error);
              }
           }
         })
      }
   }
 })   
}
上一篇:Promise入门到精通(初级篇)-附代码详细讲解


下一篇:【k8s】在K8S中部署应用