Promise

手写Promise

const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
// 三个状态的常量

function MyPromise(fn) {
  const that = this // 因为代码可能会异步执行, 用于获取正确的this对象
  that.state = PENDING // 一开始promise状态是为等待中 pedding
  that.value = null // value用于保存resolve或者reject中传入的值
  that.resolvedCallbacks = [] // 用于保存then中的回调
  that.rejectedCallbacks = []
  // 待完善 resolve 和 reject 函数
  function resolve(value) {
    if (that.state = PENDING) { // 判断是否在等待中, 规范只有在等待中的转改才可以改变状态
      that.state = RESOLVED // 将当前状态更改为对应状态, 并且将传入的值给value
      that.value = value
      that.resolvedCallbacks.map(cb => cb(that.value)) // 遍历回调函数并执行
    }
  }

  function reject(value) {
    if (that.state = PENDING) {
      that.state = REJECTED
      that.value = value
      that.rejectedCallbacks.map(cb => cb(that.value))
    }
  }
  // 待完善执行 fn 函数
  try {
    fn(resolve, reject)
  } catch (e) {
    reject(e)
  }

}
// 封装then
MyPromise.prototype.then = function(onFulfilled, onRejected) { // 判断两个参数是否为函数类型, 因为这两个参数都是可选参数
  const that = this
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
  onRejected =
    typeof onRejected === 'function'
      ? onFulfilled
      : r => {
        throw r
      }
  if (that.state === PENDING) {
    that.resolvedCallbacks.push(onFulfilled)
    that.rejectedCallbacks.push(onRejected)
  }
  if (that.state === RESOLVED) {
    onFulfilled(that.value)
  }
  if (that.state === REJECTED) {
    onRejected(that.value)
  }
}

new MyPromise((resolve, reject) => {
  setTimeout(() => {
      resolve(1)
  }, 300);
}).then(v=>{
  console.log(v)
})
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值