Promise的简单实现

Promise的简单实现

Promise本意是承诺.主要目的是为了解决在需要多个异步操作的时候.产生的回调嵌套.在es6没出来前.用bluebird来实现.与javas中的Q模块类似.

Promise对象实例创建的过程中有三种状态, Pending、Fulfilled、Rejected. Fulfilled与Rejected间不能相互转换

promise

promise的使用与原理实现

then

promise.then用于链式调用,每次执行时都会返回一个新的promise对象

all

接收一个promise数组,如果状态都为resolve则返回Promise的resolve状态,如果某个promise状态为reject则返回Promise的reject状态

race

接收一个promise数组, 比谁跑的快.返回第一完成的Promise状态

promise功能的简单实现

function Promise1 (executor) {
  let self = this
  self.status = 'pending'
  self.value = undefined
  self.onResolveCallbacks = []
  self.onRejectedCallbacks = []

  function resolve (value) {
    setTimeout(() => {
      self.value = value
      self.status = 'resolve'
      self.onResolveCallbacks.forEach(item => item(value))
    })
  }
  function reject (value) {
    setTimeout(() => {
      self.value = value
      self.status = 'reject'
      self.onRejectedCallbacks.forEach(item => item(value))
    })
  }

  try {
    executor(resolve, reject)
  } catch(e) {
    reject(e)
  }
}

function resoolvePromise (promise, x, resolve, reject) {
  if (x === promise) {
    throw new TypeError('循环引用')
  }
  let then
  if ((x !== null)&& (typeof x === 'function' || typeof x === 'object')) {
    then = x.then // x为promise
    then.call(x, function (value) {
      resolvePromise(promise, value, resolve, reject)
    }, function (reason) {
      reject(reason)
    })
  } else {
    resolve(x)
  }
}

Promise1.prototype.then = function (onFulfilled, onRejected) {
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled: function(value){ return value }
  onRejected = typeof onRejected === 'function' ? onRejected: function(value){ return value }
  let self = this
  let promise2
  if (self.status === 'resolve') {
    promise2 = new Promise(function (resolve, reject) {
      try {
        let x = onFulfilled(self.value) // x是第二个primise运行的返回值
        resoolvePromise(promise2, x, resolve, reject)
      } catch(e) {
        reject(e)
      }
    })
  }
  // reject
  if (self.status === 'reject') {
    promise2 = new Promise(function (resolve, reject) {
      try {
        let x = onRejected(self.value) // x是第二个primise运行的返回值
        resoolvePromise(promise2, x, resolve, reject)
      } catch(e) {
        reject(e)
      }
    })
  }
  if (self.status === 'pending') {
    promise2 = new Promise(function (resolve, reject) {
      self.onResolveCallbacks.push(function () {
        let x = onFulfilled(self.value) // x是第二个primise运行的返回值
        resoolvePromise(promise2, x, resolve, reject)
      })
      self.onRejectedCallbacks.push(function () {
        let x = onRejected(self.value) // x是第二个primise运行的返回值
        resoolvePromise(promise2, x, resolve, reject)
      })
    })
  }
  return promise2
}

Promise1.prototype.catch = function (onRejected) {
  return this.then(null, onRejected)
}

Promise1.all = function (promise) {
  new Promise1(function (resolve, reject) {
    let result = []
    let count = 0
    for (let i = 0; i < promise.length; i++) {
      promise[i](function (value) {
        result[i] = value
        if (++count === promise.length) {
          resolve(result)
        }
      }, function (reject) {
        reject(result)
      })
    }
  })
}

Promise1.race = function (promise) {
  new Promise1(function (resolve, reject) {
    for (let i = 0; i < promise.length; i++) {
      promise[i](function (value) {
        resolve(result)
      }, function (reject) {
        reject(result)
      })
    }
  })
}

module.exports = Promise
Promise是一种用于处理异步操作的JavaScript对象。它提供了一种更优雅和可读性更高的方式来处理异步代码,避免了回调地狱的问题。Promise有三个状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。当Promise的状态发生改变时,会触发相应的回调函数。 以下是一个简单Promise实现原理的例子: ```javascript class MyPromise { constructor(executor) { this.status = 'pending'; this.value = undefined; this.reason = undefined; this.onResolvedCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled'; this.value = value; this.onResolvedCallbacks.forEach((callback) => callback()); } }; const reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach((callback) => callback()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value; onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason; }; const promise2 = new MyPromise((resolve, reject) => { if (this.status === 'fulfilled') { setTimeout(() => { try { const x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.status === 'rejected') { setTimeout(() => { try { const x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.status === 'pending') { this.onResolvedCallbacks.push(() => { setTimeout(() => { try { const x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { const x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); } }); return promise2; } resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise')); } if (x instanceof MyPromise) { x.then(resolve, reject); } else { resolve(x); } } catch(onRejected) { return this.then(null, onRejected); } } ``` 这个例子展示了一个简单Promise实现,包括Promise的构造函数、状态的改变、回调函数的执行、链式调用以及错误处理等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值