手摸手教你写 Promise

function MyPromise(func) {
  this.status = 'pending' // resolve, reject
  this.thenFuncs = []
  this.catchFuncs = []
  this.value = undefined
  func(MyPromise.resolve.bind(this), MyPromise.reject.bind(this))
}

MyPromise.resolve = function(result) {
  this.value = result
  this.status = 'resolve'
  this.thenFuncs.forEach(func => func(result))
}

MyPromise.reject = function(error) {
  this.value = error
  this.status = 'reject'
  this.catchFuncs.forEach(func => func(error))
}

MyPromise.prototype.then = function(thenFunc) {
  if (this.status === 'resolve') {
    thenFunc(this.value)
  } else {
    this.thenFuncs.push(thenFunc)
  }
  return this
}

MyPromise.prototype.catch = function(catchFunc) {
  if (this.status === 'reject') {
    catchFunc(this.value)
  } else {
    this.catchFuncs.push(catchFunc)
  }
  return this
}

// ----- start ----------
new MyPromise((resolve, reject) => {
  if (false) {
    setTimeout(() => {
      resolve(123)
    }, 3000)
  } else {
    reject('error')
  }
}).then(result => {
  console.log(result)
}).then(result => {
  console.log(result)
}).then(result => {
  console.log(result)
}).catch(error => {
  console.log(error)
}).catch(error => {
  console.log(error)
}).catch(error => {
  console.log(error)
})

我们会发现我们用自己封装的 Promise 的时候,当我们 new Promise 里传的不是异步方法,那它的 .then 会优先执行,这和原生的 Promise 有些不符

其实是因为原生的 Promise 将任务添加到了微任务里边

用到了 window 的 queueMicrotask API

queueMicrotask(() => {
  /* 微任务中将运行的代码 */
});

猜你喜欢

转载自blog.csdn.net/weixin_42335036/article/details/119868524