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)
}

  

转载于:https://www.cnblogs.com/wjgoblin/p/11279081.html

你可能感兴趣的:(js简单实现promise)