zoukankan      html  css  js  c++  java
  • Promise A/+ 简单实现

    function Promise(exec){
      var self = this
      self.status = 'pending'//状态没用到。。。
      self.onResolvedList = []//当进行链式调用时,推入到列表
      self.onRejectedList = []//当进行链式调用时,推入到列表
      function resolved(reason){
        // if(self.status !== 'pending')return
        self.status = 'fulfilled'
        setTimeout(function(){//exec为同步函数时,将任务推到后面执行

          onResolvedList.forEach(function(fn){

            fn(reason)       

          })

        },0)
      }

      function rejected(reason){
        // if(self.status !== 'pending')return
        self.status = 'rejected'
        setTimeout(function(){//exec为同步函数时,将任务推到后面执行
          onRejectedList.forEach(function(fn){

            fn(reason)       

          })
        },0)
      }
      exec(resolved,rejected)//构造函数执行
    }

    Promise.prototype.then = function(resolved,rejected){
      var self = this
      self.onResolvedList.push(resolved)
      self.onRejectedList.push(rejected)
      return self
    }
    var P = new Promise(function(resolve,reject){
      // setTimeout(function(){
        resolve("resolve")
      // }, 1000)
    })
    P.then(function(value){
      console.log(value)
    }).then(function(value){
      setTimeout(function(){
        console.log(value)
      },1000)
    })

  • 相关阅读:
    注解
    使用反射机制调用属性和私有成员与代理模式的介绍
    动态代理模式
    SVN的安装与常用功能使用以及解决安装配置过程中的一些错误
    企业私服
    -Java-log4j
    List,Set,Map用法以及区别
    接口和抽象类有什么区别
    Dalvik opcodes
    外派公司或者外包公司,真的适合选择吗?
  • 原文地址:https://www.cnblogs.com/mooniitt/p/6774867.html
Copyright © 2011-2022 走看看