手写promise

2019-09-25  本文已影响0人  曹锦花
function MyPromise(callback) {
  // 定义 promise 内部的 status 和 value 值
  let _this = this
  this.status = 'pending'
  this.value = null
  this.resolveFunArr = []
  this.rejectFunArr = []

  function resolve(value) {
    if (_this.status === 'pending') {
      _this.status = 'resolved'
      _this.value = value
      _this.resolveFunArr.forEach(item => {
        item(_this.value)
      });
    }
  }
  function reject(value) {
    if (_this.status === 'pending') {
      _this.status = 'rejected'
      _this.value = value
      _this.rejectFunArr.forEach(item => {
        item(_this.value)
      })
    }
  }
  // try {
  callback(resolve, reject)
  // } catch (err) {
  // reject(err)
  // }
}

MyPromise.prototype.then = function (resolve, reject) {
  let _this = this
  if (_this.status == 'resolved') {
    resolve(_this.value)
  }

  if (_this.status == 'resolved') {
    reject(_this.value)
  }
  if (_this.status == 'pending') {
    _this.resolveFunArr.push(resolve)
    _this.rejectFunArr.push(reject)
  }
}

var testPromise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    var number = Math.random();
    if (number <= 0.5) {
      resolve('less than 0.5');
    } else {
      reject('greater than 0.5');
    }
  }, 1000)
})

testPromise.then(data => {
  console.log(data)
}, dataReject => {
  console.log(dataReject)
})
上一篇 下一篇

猜你喜欢

热点阅读