手写Promise

2019-06-11  本文已影响0人  梦不成

基本实现new Promise 和 then /catch方法

class Promise {
  constructor(excutorCallback) {
    this.status = 'pending' //new Primise 时为进行中
    this.value = undefined //resolve/reject的初始值(参数)
    
    this.fulfilledAry = [] //成功之后要做的事
    this.rejectedAry = [] //失败之后要做的事

    let resolveFn = result => {
      let timer = setTimeout(() => {
        clearTimeout(timer)  
        if (this.status !== 'pending') return
        this.status = 'fulfilled'
        this.value = result

        this.fulfilledAry.forEach(item => {
          item(this.value)
        })
        }, 0)
    }

    let rejectFn = reason => {
      let timer = setTimeout(() => {
        clearTimeout(timer)
        if (this.status !== 'pending') return
        this.status = 'rejected'
        this.value = reason

        this.rejectedAry.forEach(item => {
          item(this.value)
        })
      }, 0)
    }

    //实例化时异常捕获
    try {
      excutorCallback(resolveFn, rejectFn)
    } catch (err) {
      //异常按rejected状态处理
      rejectFn(err)
    }
  }

  //原型上加方法
  then (fulfilledCallback, rejectedCallback) {
    //then的参数不传的情况 给它一个函数以承接数据 在后面的then里面就可以拿到了
    typeof fulfilledCallback !== 'function' ? fulfilledCallback = result => result : null

    typeof rejectedCallback !== 'function' ? rejectedCallback = reason => {
      throw new Error(reason.message)
    } : null

    //链式操作返回一个新的Promise实例
    return new Promise((resolve, reject) => {
      this.fulfilledAry.push(() => {
        try {
          let x = fulfilledCallback(this.value)
          x instanceof Promise ? x.then(resolve, reject) : resolve(x)
        } catch (err) {
          reject(err)
        }
        
      })
      this.rejectedAry.push(() => {

        try {
          let x = rejectedCallback(this.value)
          x instanceof Promise ? x.then(resolve, reject) : resolve(x)
        } catch (err) {
          reject(err)
        }
      })
    })
  }

  //原型上添加catch方法
  catch (rejectedCallback) {
    return this.then(null, rejectedCallback)
  }
}

module.exports = Promise
const Promise = require('./Promise')

new Promise((resolve, reject) => {

  // throw new Error('wrong')
  resolve(100)

  reject(-100)

}).then((result) => {
  console.log(result);
  console.log('成功')
  
}, (reason) => {
  console.log(reason)
  console.log('失败')

})

console.log('同步方法');
上一篇 下一篇

猜你喜欢

热点阅读