美文网首页
Promise then 方法多次调用

Promise then 方法多次调用

作者: 湘兰沅芷 | 来源:发表于2021-12-13 23:04 被阅读0次
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功')
  }, 2000)
  // resolve('成功')
  // reject('失败')
})
promise.then(value => {
  console.log(value);
}, reason => {
  console.log(reason)
})
promise.then(value => {
  console.log(value);
}, reason => {
  console.log(reason)
})
promise.then(value => {
  console.log(value);
}, reason => {
  console.log(reason)
});
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected'// 失败
class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject)
  }
  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []
  resolve = value => {
    if (this.status !== PENDING) return
    // 将状态修改为成功
    this.status = FULFILLED
    // 保存成功之后的值
    this.value = value
    // this.successCallback && this.successCallback(this.value)
    while(this.successCallback.length) {
      this.successCallback.shift()(this.value)
    }
  }
  reject = reason => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // this.failCallback && this.failCallback(this.reason)
    while(this.failCallback.length) {
      this.failCallback.shift()(this.reason)
    }
  }
  then(successCallback, failCallback) {
    if (this.status === FULFILLED) {
      successCallback(this.value)
    } else if (this.status === REJECTED) {
      failCallback(this.reason)
    } else {
      // 等待
      // 讲成功回调和失败回调进行存储
      this.successCallback.push(successCallback)
      this.failCallback.push(failCallback)
    }
  }
}

module.exports = MyPromise

相关文章

网友评论

      本文标题:Promise then 方法多次调用

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