手写Promise

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

  • Promise.js
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
  • test.js测试 调用手写的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('同步方法');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容