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

  • 相关阅读:
    「CF1335E Three Blocks Palindrome」
    「高等数学学习笔记 DAY23」
    「高等数学学习笔记 DAY22」
    「CF911G Mass Change Queries」
    「CF689D Friends and Subsequences」
    「高等数学学习笔记 DAY21」
    「高等数学学习笔记 DAY20」
    「高等数学学习笔记 DAY19」
    「Luogu P6242 【模板】线段树 3」
    【POJ3278】Catch That Cow
  • 原文地址:https://www.cnblogs.com/mooniitt/p/6774867.html
Copyright © 2011-2022 走看看