手写一个简化版的 Promise

187 阅读1分钟

Promise的语法封装:

  • promise规定不管是失败回调还是成功回调,都只能接受一个参数
  • this就是.call的第一个函数

代码实现:

class Promise2 {
  #status = 'pending'
  constructor(fn){
    this.q = []
    const resolve = (data)=>{
      this.#status = 'fulfilled'
      const f1f2 = this.q.shift()
      if(!f1f2 || !f1f2[0]) return
      const x = f1f2[0].call(undefined, data)
      if(x instanceof Promise2) {
        x.then((data)=>{
          resolve(data)
        }, (reason)=>{
          reject(reason)
        })
      }else {
        resolve(x)
      }
    }
    const reject = (reason)=>{
      this.#status = 'rejected'
      const f1f2 = this.q.shift()
      if(!f1f2 || !f1f2[1]) return
      const x = f1f2[1].call(undefined, reason)
      if(x instanceof Promise2){
        x.then((data)=>{
          resolve(data)
        }, (reason)=>{
          reject(reason)
        })
      }else{
        resolve(x)
      }
    }
    fn.call(undefined, resolve, reject)
  }
  then(f1, f2){
    this.q.push([f1, f2])
  }
}

const p = new Promise2(function(resolve, reject){
  setTimeout(function(){
    reject('出错')
  },3000)
})

p.then( (data)=>{console.log(data)}, (r)=>{console.error(r)} )

总结:

  • Promise 不是前端发明的;
  • Promise 是目前前端解决异步问题的统一方案
  • window.Promise 是一个全局函数,可以用来构造 Promise 对象
  • 使用 return new Promise((resolve, reject)=> {}) 就可以构造一个 Promise 对象
  • 构造出来的 Promise 对象含有一个 .then() 函数属性