Promise

139 阅读1分钟

手写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)
})