其他分享
首页 > 其他分享> > js类似promise的手写实现

js类似promise的手写实现

作者:互联网

function MyPromise(func){
            this.status = "pending";
            this.rightResult = null;
            this.errorResult = null;
            this.errorFunction = true;
            this.out = false;
            let self = this
            function resolve(value){
                if(self.out) return 
                self.status = 'resolved'
                self.rightResult = value
                self.out = true
            };
            function reject(value){
                if(self.out) return 
                self.status = 'rejected'
                self.errorResult = value
                self.out = true
            };
            try{
                func(resolve,reject)
            }catch(e){
                console.log(e)
            }
        }
    MyPromise.prototype.then = function(onResolved,onRejected){
          if (typeof onRejected !== 'function'){
              this.errorFunction = false
          }
          if(this.status === 'resolved' && typeof onResolved === 'function'){
              onResolved(this.rightResult)
          }
          else if(this.status === 'rejected' && typeof onResolved === 'function'){
              onRejected(this.errorResult)
          }
      }
      MyPromise.prototype.catch = function(onRejected){
          if(this.status = 'rejected' && !this.errorFunction){
              onRejected(this.errorResult)
          }
      }

标签:function,status,self,js,promise,onResolved,手写,onRejected,out
来源: https://blog.csdn.net/xin_sleep/article/details/122307647