手写一个自己的 Promise

2019-01-04  本文已影响0人  野鸡没名
常言道:“知其然,更要知其所以然”
所谓JS本身是“函数式,异步”编程(回调地狱,你懂的),Promise得出现,让JS写起来好像是“同步编程”得感觉了!
下面是基于我自己对Promise得理解,用ES6语法写了一个Promise

第二版【19-10-26】🤣🤗😍🙃

class Promise2 {
  constructor(cb) {
    this.success = []
    this.field = []
    this.status = 'pedding'
    this.successData
    this.fieldData

    cb(data => this.resolve(data), err => this.reject(err))
  }

  resolve(successData) {
    this.status = 'success'
    this.successData = successData
    this.handleSucc()
  }

  reject(fieldData) {
    this.status = 'field'
    this.fieldData = fieldData
    this.handleField()
  }

  then(succFu, errorFn) {
    this.success.push(succFu)
    this.field.push(errorFn)

    if (this.status === 'success') {
      this.handleSucc()
    } else if (this.status === 'field') {
      this.handleField()
    }

    return this
  }

  handleSucc() {
    if (this.success.length) {
      this.successData = this.success.shift()(this.successData)
      this.handleSucc()
    }
  }

  handleField() {
    if(this.field.length) {
      this.fieldData = this.field.shift()(this.fieldData)
      this.handleField()
    }
  }
}

// 测试代码
const p = new Promise2((res, rej) => {
  setTimeout(() => {
    res('11111111111111')
  }, 2000)
})

p.then((res) => {
  console.log(res)

  return '222222222222222'
}).then(res => {
  console.log(res)

  return '333333333333333'
}).then(res => {
  console.log(res)
})

第一版【19-01-04】我还是个小渣渣 😶

// 既然Promise使用得时候是通过new得到的,那么首先分析出Promise是一个类
class Promise2 {
    // Promise接收一个回调函数作为参数,这里将回调函数fn传入构造中
    constructor (fn) {
        let _this = this
        this.success_res = null // success_res保存的是“成功回调” -> resolved执行时候传递得结果
        this.error_res = null // error_res保存的是“失败回调” -> rejected执行时候传递的结果
        /**
         * Promise的核心重点就在于“状态”
         * 如果操作结果还没有成功或者失败,那么then传进来的两个回调函数,就会被“挂起”
         */
        this.state = 'pending' // 还没得到成功或失败的结果状态
        this.fnArr = [] // 保存挂起的回调函数 -> 外部调用then时传进来的回调函数,这里将它们“队列”起来

        function resolved (...args) { // 如果传入的值是多个,那么直接用...运算符“打包”
            _this.success_res = args // 记录成功得到的数据
            _this.state = 'success' // 改变状态
            _this.fnArr.forEach(json => json.success(_this.success_res)) // 执行“挂起”的成功回调
        }
        function rejected (...args) {
            _this.error_res = args
            _this.state = 'error'
            _this.fnArr.forEach(json => json.error(_this.error_res))
        }

        fn(resolved, rejected) // 将成功、失败两个回调传回给调用处
    }

    /**
     * then是根据状态,控制下一步该怎么做的关键
     * 成功、失败都会执行对应的回调,并且回传结果
     * 那么当没有结果时候怎么办呢?直接挂起即可
     * 挂起后的函数什么时候执行呢?成功、失败的时候,直接去挂起的“队列”中取出来,并且执行
     */
  then (success, error) {
    if (this.state === 'success') success(this.success_res)
    if (this.state === 'error') {
      error(this.error_res)
      this.catch(this.error_res)
    }
    if (this.state === 'pending') this.fnArr.push({ success, error })

    return this // 链式then,你懂得
  }

  catch(err) {
    return this
  }

}
好啦小伙伴们,我们来试着用一用 o( ̄▽ ̄)o
new Promise2((resolved, rejected) => {
    setTimeout(() => {
        resolved('success')
    }, 1000)
    // rejected('error')
})
    .then(res => {
        console.log(res)
    }, err => {
        console.log(err)
    })

20180918102221878.png
控制台打印出了这么个东西,是个数组没错,因为我的Promise支持传多个参数 ( ̄▽ ̄)"

总结一下

Promise的本质就是一种 状态管理机制

我是如何理解并且手写出来一个自己的Promise的?首先我想说说对js函数式编程的理解。
异步函数式编程的核心在于“将函数当作函数的参数传递”,是不是有点绕?(●ˇ∀ˇ●)
如果你对函数的“传递”理解的深了,那么恭喜你!你会对js这种回调函数式编程有了更高一层的认识

场景意淫 -> “封装后的函数,方法怎么用”?

php程序员:“传递参数”
java程序员:“传递参数+传递类型(泛型)”
javascriptER: “函数里面传函数” ( ̄▽ ̄)"

上一篇 下一篇

猜你喜欢

热点阅读