美文网首页
手动实现promise

手动实现promise

作者: 想当一个大头兵 | 来源:发表于2019-08-06 16:28 被阅读0次

具体版本应该是通过setTimeout(f,0)来模拟pedding转化状态,下面是为了方便理解跟面试,写了个简略版本的。

function promise () {

  this.status = 'pending' // 2.1

  this.msg = '' // 存储value与reason

  let process = arguments[0],

      that = this

  process (function () {

    that.status = 'resolve'

    that.msg = argument[0]

  }, function () {

    that.status = 'reject'

    that.msg = argument[0]

  })

  return this

}

promise.prototype.then = function () {

  if (this.status === 'resolve') {

    arguments[0](this.msg)

  } else if (this.status === 'reject' && arguments[1]) {

    arguments[1](this.msg)

  }

}

ƒ () {

  if (this.status === 'resolve') {

    arguments[0](this.msg)

  } else if (this.status === 'reject' && arguments[1]) {

    arguments[1](this.msg)

  }

}

相关文章

网友评论

      本文标题:手动实现promise

      本文链接:https://www.haomeiwen.com/subject/iddwdctx.html