0
点赞
收藏
分享

微信扫一扫

js类似promise的手写实现

钵仔糕的波波仔 2022-01-04 阅读 76
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)
          }
      }
举报

相关推荐

0 条评论