6行代码实现Promise

115 阅读1分钟
   const Promise = function(f) {
      this.__f = f;
    }
    Promise.prototype.then = function(resolve=()=>null,reject=()=>null) {
      return this.__f(resolve,reject)
    }
使用方式
    const getJson = function() {
      return new Promise((resolve, reject) => {
        setTimeout(function(){
          resolve({name:'张三'})
        },3000)
      })
    }
    const res = getJson()
    res.then(data => {
      console.log(data)
    })