js简单实现promise

function myPromise(fn){
      let status='pending',successCallback=[],failedCallback=[],data=null,reason=null
      this.then=function(fulfilled,rejected){
          if(status=='pending'){
                  successCallback.push(fulfilled)
                  failedCallback.push(rejected)
                  return this
           }else if(status=='fulfilled'){
                   fulfilled(data)
           }else{
                  rejected(reason)
            }
        }
      function resolve(value){
             process.nextTick(
                    status='faifilled'
                    data=value
                    function(){successCallback.forEach((callback)=>callback(value))
               })
       }
      function reject(value){
              process.nextTick(
                    status='rejected'
                    reason=value
                    function(){failedCallback.forEach((value)=>callback(value))
               })
       }
      fn(resolve,reject)
}

  

posted @ 2019-07-31 21:04  dawn~monster  阅读(373)  评论(0编辑  收藏  举报