Promise分析与实现(上篇)

Promise分析与实现

分析原生Promise

1.Promise接受一个参数,且参数只能为函数,其函数的参数为两个函数
let p = new Promise((resolve, reject) => {
    
})

参数只能为函数,否则抛出错误

var res = 1
let p = new Promise(res)

在这里插入图片描述

2. Promise本身就是一个状态机,其有三种状态:pending, fullfilled, rejected. 还可以得出两个内部属性:[[PromiseStatus]],[[PromiseValue]]

状态只能由 Pending 变为 Fulfilled 或由 Pending 变为 Rejected ,且状态改变之后不会在发生变化,会一直保持这个状态

不调用函数时

let p = new Promise((resolve, reject) => {

})
console.log(p)

在这里插入图片描述

调用resolve时

let p = new Promise((resolve, reject) => {
  resolve("调用了resolve")
})
console.log(p)

在这里插入图片描述

调用reject时

let p = new Promise((resolve, reject) => {
  reject("调用了reject")
})
console.log(p)

在这里插入图片描述

3.Promise的实例有一个then方法,接收两个函数参数

调用resolve,then的第一个函数参数执行
调用reject,then的第二个函数参数执行

let p = new Promise((resolve, reject) => {
  resolve("调用了resolve")
})
    
p.then(res => {
  console.log(res)
}, err => {
  console.log(err)
})
4.Promise的then方法支持多次调用
let promise1 = new Promise((resolve, reject) => {
  resolve('1')
})
promise1.then(res => {
  console.log(res)
})
promise1.then(res => {
  console.log(res)
})

打印结果:

在这里插入图片描述

5.Promise的微任务
setTimeout(function(){
  console.log(2)
}, 0)
let promise1 = new Promise((resolve, reject) => {
  resolve('1')
})
promise1.then(res => {
  console.log(res)
})

打印结果:
在这里插入图片描述

6.Promise的then返还一个Promise对象,可链式调用
let promise1 = new Promise((resolve, reject) => {
  resolve('1')
})
promise1.then(res => {
  console.log(res)
  return res
}).then(res => {
  console.log(res)
})

打印结果:
在这里插入图片描述

7.Promise的then接收Promise对象或返回结果时进行不同操作

当返回值不是Promise对象时 ,则直接将返回值作为新返回的 Promise 对象的值, 即then的res或err的参数

let promise1 = new Promise((resolve, reject) => {
  resolve()
})
promise2 = promise1.then(res => {
  // 当return一个不是Promise对象的值
  return 'return一个不是Promise对象的值'
})
promise2.then(res => {
  console.log(res) //打印出:return一个不是Promise对象的值
})

在这里插入图片描述

当返回值为Promise对象时 ,这时后面一个回调函数,就会等待返回的这个Promise对象的状态发生变化时(执行resolve()或reject()时),才会被调用,并且新的Promise状态和返回的这个Promise对象的状态相同。

let promise1 = new Promise((resolve, reject) => {
  resolve()
})
promise2 = promise1.then(res => {
  // 返回一个Promise对象
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('return一个Promise对象')
    }, 2000)
  })
})
promise2.then(res => {
  console.log(res) //2秒后打印出:return一个Promise对象
})

在这里插入图片描述

8.Promise的then抛出异常时

如果 onFulfilled 或者onRejected 抛出一个异常 err ,则返回的Promise对象的状态必须变为失败Rejected,并返回失败的值 err

let promise1 = new Promise((resolve, reject) => {
  resolve('success')
})
promise2 = promise1.then(res => {
  throw new Error('这里抛出一个异常err')
})
promise2.then(res => {
  console.log(res)
}, err => {
  console.log(err) //打印出:这里抛出一个异常err
})

在这里插入图片描述

9.Promise的then的值穿透

值穿透是个常见的面试题

当then的onFulfilled参数不是函数时,返回的Promise对象的状态必须变成fulfilled,并返回调用then的Promise的成功的值

let promise1 = new Promise((resolve, reject) => {
  resolve('success')
})
promise2 = promise1.then('then的第一个参数不是函数了')
promise2.then(res => {
  console.log(res) // 打印出:success
}, err => {
  console.log(err)
})

在这里插入图片描述

当then的onRejected参数不是函数时,返回的Promise对象的状态必须变成rejected,并返回调用then的Promise的失败的值

let promise1 = new Promise((resolve, reject) => {
  reject('fail')
})
promise2 = promise1.then(res => res, 'then的第二个参数不是函数了')
promise2.then(res => {
  console.log(res)
}, err => {
  console.log(err) // 打印出:fail
})

在这里插入图片描述

LuPromise的编写

1.实现Promise分析的第1、2点

通过new Promise可知,Promise是一个类,那么现在来实现一个class LuPromise。

1.首先,必须接收一个函数作为参数,不是函数则抛出错误
2.且拥有 [[PromiseStatus]],[[PromiseValue]]两个内部属性
3.当Promise内部什么都不调用时,status值为pending,value值为undefined

// 判断是否是函数
const isFunction = f => typeof f === 'function'
// 定义Promise的三种状态常量
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'

class LuPromise {
  constructor (handle) {
    // 如果参数不是函数
    if (!isFunction(handle)) {
      // 不是函数就抛出错误
      throw new Error('LuPromise必须接收函数类型的参数')
    }
    // 添加状态属性 status [[promiseStatus]]
    this._status = PENDING
    // 添加Promise的值 value [[promiseValue]]
    this._value = undefined
  }
}

接下来是验证

当参数不为函数时

var res = 1
let p = new LuPromise(res)

抛出错误成功!
在这里插入图片描述

当LuPromise内部不执行调用时,打印value和status值

let p = new LuPromise((resolve, reject) => {
})
console.log(p)

状态和值成功!
在这里插入图片描述

2.LuPromise的函数参数接收两个函数,并可以在内部调用
// 判断是否是函数
const isFunction = f => typeof f === 'function'
// 定义Promise的三种状态常量
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'

class LuPromise {
  constructor (handle) {
    // 如果参数不是函数
    if (!isFunction(handle)) {
      // 不是函数就抛出错误
      throw new Error('LuPromise必须接收函数类型的参数')
    }
    // 添加状态属性 [[promiseStatus]]
    this._status = PENDING
    // 添加Promise的值 [[promiseValue]]
    this._value = undefined
    // 执行handle后,这两个函数也就相当于了内部函数 高阶函数
    handle(function(val){
      // resolve
      // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
      if (this._status !== PENDING) return
      this._status = FULFILLED
      this._value = val
    }.bind(this), function(err){
      // reject
      // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
      if (this._status !== PENDING) return
      this._status = REJECTED
      this._value = err
    }.bind(this))

  }
}
LuPromise中调用resolve和reject

调用resolve

let p = new LuPromise((resolve, reject) => {
  resolve('11')
})
console.log(p)

在这里插入图片描述

调用reject

let p = new LuPromise((resolve, reject) => {
  reject('22')
})
console.log(p)

在这里插入图片描述

这一步实现了让handle内部的两个函数参数在handle执行后,变成了LuPromise的内部函数,可以通过内部直接调用,也就是resolve()和reject()
至于bind(this),可以知道resolve()和reject()调用时,this指向window,因此通过bind绑定一下this,当然这里也可将函数写成箭头函数,但是不利于后面的编写

3.将第二步封装一下,把匿名函数写出来
// 判断是否是函数
const isFunction = f => typeof f === 'function'
// 定义Promise的三种状态常量
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'

class LuPromise {
  constructor (handle) {
    // 如果参数不是函数
    if (!isFunction(handle)) {
      // 不是函数就抛出错误
      throw new Error('LuPromise必须接收函数类型的参数')
    }
    // 添加状态属性 [[promiseStatus]]
    this._status = PENDING
    // 添加Promise的值 [[promiseValue]]
    this._value = undefined
    try {
      // 执行handle后,这两个函数也就相当于了内部函数 高阶函数
      handle(this._resolve.bind(this), this._reject.bind(this))
    } catch (error) {
      this._reject(error)
    }
  }
  
  _resolve (val) {
    // resolve
    // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
    if (this._status !== PENDING) return
    this._status = FULFILLED
    this._value = val
  }

  _reject (err) {
    // reject
    // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
    if (this._status !== PENDING) return
    this._status = REJECTED
    this._value = err
  }
}
4. then方法,实现调用resolve和reject分别触发相关函数(错误写法) 手写过程中碰到的

then方法在class LuPromise内部

// then方法
then (onFUlfilled, onRejected) {
  const { _value, _status } = this
  // 判断有就执行
  onFUlfilled && onFUlfilled(_value)
  // 判断有就执行
  onRejected && onRejected(_value)
}

调用resolve

let p = new LuPromise((resolve, reject) => {
  resolve('resolve调用了')
})
// console.log(p)
p.then(res => {
  console.log(res)
}, err => {
  console.log(err)
})

在这里插入图片描述

调用reject

let p = new LuPromise((resolve, reject) => {
  reject('reject调用了')
})
// console.log(p)
p.then(res => {
  console.log(res)
}, err => {
  console.log(err)

在这里插入图片描述
可以看到,已经实现了then
但是,这是错误的,来看看这个

将resolve放在setTimeout中

let p = new LuPromise((resolve, reject) => {
  setTimeout(function(){
    resolve('resolve调用了')
  }, 1000)
})
// console.log(p)
p.then(res => {
  console.log(res)
}, err => {
  console.log(err)
})

这是打印结果:空白,什么都没有打印

在这里插入图片描述

在then方法中添加几行代码,就可以看出其原因了

// then方法
then(onFUlfilled, onRejected) {
  const {
    _value,
    _status
  } = this
  if (_status === FULFILLED) {
    // 判断有就执行
    onFUlfilled && onFUlfilled(_value)
  } else if (_status === REJECTED) {
    // 判断有就执行
    onRejected && onRejected(_value)
  } else if (_status === PENDING) {
    console.log('pending')
  }
}

这是打印结果:pending!
这里可以看出then中方法并不是在resolve执行后调用,所以现在需要实现的就是调用resolve和reject后调用相关函数

在这里插入图片描述
接下来就是解决这个错误啦

5.实现Promise分析中第3点和第4点:可多次调用then和调用resolve、reject时触发函数

由于then方法支持多次调用,可以使用两个队列来保存onFUlfilled和onRejected函数,并在resolve和reject调用后触发

constructor

添加两个队列_fulfilledArray ,_rejectedArray

constructor (handle) {
  // 如果参数不是函数
  if (!isFunction(handle)) {
    // 不是函数就抛出错误
    throw new Error('LuPromise必须接收函数类型的参数')
  }
  // 添加状态属性 [[promiseStatus]]
  this._status = PENDING
  // 添加Promise的值 [[promiseValue]]
  this._value = undefined
  // 添加成功回调函数事件队列
  this._fulfilledArray = []
  // 添加失败回调函数事件队列
  this._rejectedArray = []
  try {
    // 执行handle后,这两个函数也就相当于了内部函数 高阶函数
    handle(this._resolve.bind(this), this._reject.bind(this))
  } catch (error) {
    this._reject(error)
  }
then
// then方法
then(onFUlfilled, onRejected) {
  const {
    _value,
    _status
  } = this

  switch (_status) {
    // 当状态还是进行中时,把两个方法都加入到回调函数事件队列中
    case PENDING:
      this._fulfilledArray.push(onFUlfilled)
      this._rejectedArray.push(onRejected)
      break
      // 当状态改变成Fulfilled时,直接触发onFulfilled函数
    case FULFILLED:
      onFUlfilled(_value)
      break
      // 当状态改变成Rejected时,直接触发onRejected函数
    case REJECTED:
      onRejected(_value)
      break
  }
_resolve和reject
_resolve(val) {
  // resolve
  // 先检测Promise的状态是否是PENDING,如果不是,就直接返
  if (this._status !== PENDING) return
  const run = () => {
    this._status = FULFILLED
    this._value = val
    let CallBack;
    // 获取成功队列中的第一个回调函数,执行
    while (CallBack = this._fulfilledArray.shift()) {
      CallBack && CallBack(val)
    }
  }
  // 为了先保存函数,然后再执行,所以放在了setTimeout中
  setTimeout(run)
}
_reject(err) {
  // reject
  // 先检测Promise的状态是否是PENDING,如果不是,就直接返
  if (this._status !== PENDING) return
  // 依次执行失败队列中的函数,并清空队列
  const run = () => {
    this._status = REJECTED
    this._value = err
    let CallBack;
    // 获取失败队列中的第一个回调函数,执行
    while (CallBack = this._rejectedArray.shift()) {
      CallBack && CallBack(err)
    }
  }
  // 为了先保存函数,然后再执行,所以放在了setTimeout中
  setTimeout(run)
}

接下来看打印结果

let p = new LuPromise((resolve, reject) => {
  setTimeout(function(){
    resolve('resolve调用了')
  }, 1000)
})
p.then(res => {
  console.log(res)
}, err => {
  console.log(err)
})

在这里插入图片描述
完成了在resolve和reject调用后才触发then中相应的函数了!

6.实现Promise分析中的第5点:将LuPromise伪装为微任务
_reject和_resolve

通过mutationObserver将LuPromise伪装成微任务

_resolve(val) {
  // resolve
  // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
  if (this._status !== PENDING) return
  const run = () => {
    this._status = FULFILLED
    this._value = val
    let CallBack;
    // 获取成功队列中的第一个回调函数,执行
    while (CallBack = this._fulfilledArray.shift()) {
      CallBack(val)
    }
  }
  // 通过MutationObserver实现微任务
  let ob = new MutationObserver(run)
  ob.observe(document.body, {
    attributes: true
  })
  document.body.setAttribute("lu", Math.random())
}
_reject(err) {
  // reject
  // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
  if (this._status !== PENDING) return
  // 依次执行失败队列中的函数,并清空队列
  const run = () => {
    this._status = REJECTED
    this._value = err
    let CallBack;
    // 获取失败队列中的第一个回调函数,执行
    while (CallBack = this._rejectedArray.shift()) {
      CallBack(err)
    }
  }
  // 通过MutationObserver实现微任务
  let ob = new MutationObserver(run)
  ob.observe(document.body, {
    attributes: true
  })
  document.body.setAttribute("lu", Math.random())
}
打印
setTimeout(function(){
  console.log('setTimeout')
})
let p = new LuPromise((resolve, reject) => {
    resolve('resolve调用了')
})
p.then(res => {
  console.log(res)
}, err => {
  console.log(err)
})

LuPromise成功伪装成微任务,在setTimeout之前执行

在这里插入图片描述

7.实现Promise分析中的第6点,then返回LuPromise实例
// then方法
then(onFUlfilled, onRejected) {
  const {
    _value,
    _status
  } = this
  return new LuPromise((onFulfilledNext, onRejectedNext) => {
    switch (_status) {
      // 当状态还是进行中时,把两个方法都加入到回调函数事件队列中
      case PENDING:
        this._fulfilledArray.push(onFUlfilled)
        this._rejectedArray.push(onRejected)
        break
        // 当状态改变成Fulfilled时,直接触发onFulfilled函数
      case FULFILLED:
        onFUlfilled(_value)
        break
        // 当状态改变成Rejected时,直接触发onRejected函数
      case REJECTED:
        onRejected(_value)
        break
    }
  }) 
let p = new LuPromise((resolve, reject) => {
    resolve('resolve调用了')
})
let b = p.then()
console.log(b)

打印结果:成功返回LuPromise实例

在这里插入图片描述

8.实现Promise分析中的第7点,then根据接收的是否是LuPromise或普通值,进行不同操作
// then方法
then(onFUlfilled, onRejected) {
  const {
    _value,
    _status
  } = this
  return new LuPromise((onFulfilledNext, onRejectedNext) => {
    // 封装一个状态为Fulfilled的函数
    let fulfilled = value => {
      let result = onFUlfilled(value)
      // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
      if (result instanceof LuPromise) {
        result.then(onFulfilledNext, onRejectedNext)
      } else {
        // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
        onFulfilledNext(result)
      }
    }
    //封装一个状态为Rejected的函数
    let rejected = error => {
      let result = onRejected(error)
      // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
      if (result instanceof LuPromise) {
        result.then(onFulfilledNext, onRejectedNext)
      } else {
        // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
        onFulfilledNext(result)
      }
    }
    switch (_status) {
      // 当状态还是进行中时,把两个方法都加入到回调函数事件队列中
      case PENDING:
        this._fulfilledArray.push(fulfilled)
        this._rejectedArray.push(rejected)
        break
        // 当状态改变成Fulfilled时,直接触发fulfilled函数
      case FULFILLED:
        fulfilled(_value)
        break
        // 当状态改变成Rejected时,直接触发rejected函数
      case REJECTED:
        rejected(_value)
        break
    }
  })
}

注意这里,将之前推入队列和执行的替换成了封装的fulfilled和rejected的函数,其内部进行了对返回值的判断

9.实现Promise分析第8点,当抛出异常时,返回的Promise对象状态变成rejected并执行reject函数
// then方法
then(onFUlfilled, onRejected) {
  const {
    _value,
    _status
  } = this
  return new LuPromise((onFulfilledNext, onRejectedNext) => {
    // 封装一个状态为Fulfilled的函数
    let fulfilled = value => {
      try {
        let result = onFUlfilled(value)
        // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
        if (result instanceof LuPromise) {
          result.then(onFulfilledNext, onRejectedNext)
        } else {
          // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
          onFulfilledNext(result)
        }
      } catch (error) {
        // 如果函数出错,返回的Promise对象的状态变为rejected,并执行reject函数
        onRejectedNext(error)
      }
    }
    //封装一个状态为Rejected的函数
    let rejected = error => {
      try {
        let result = onRejected(error)
        // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
        if (result instanceof LuPromise) {
          result.then(onFulfilledNext, onRejectedNext)
        } else {
          // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
          onFulfilledNext(result)
        }
      } catch (error) {
        // 如果函数出错,返回的Promise对象的状态变为rejected,并执行reject函数
        onRejectedNext(error)
      }
    }
    
    switch (_status) {
      // 当状态还是进行中时,把两个方法都加入到回调函数事件队列中
      case PENDING:
        this._fulfilledArray.push(fulfilled)
        this._rejectedArray.push(rejected)
        break
        // 当状态改变成Fulfilled时,直接触发fulfilled函数
      case FULFILLED:
        fulfilled(_value)
        break
        // 当状态改变成Rejected时,直接触发rejected函数
      case REJECTED:
        rejected(_value)
        break
    }
  })
}

这里只是将其包裹在try-catch中,接下来看打印结果

let promise1 = new LuPromise((resolve, reject) => {
  resolve('resolve调用了')
})
promise2 = promise1.then(res => {
  throw new Error('这里抛出一个异常err')
})
promise2.then(res => {
  console.log(res)
}, err => {
  console.log(err) //打印出:这里抛出一个异常err
})

在这里插入图片描述
好,分析第8点也完成!

10.实现Promise分析第9点,then的值穿透问题
// then方法
then(onFUlfilled, onRejected) {
  const {
    _value,
    _status
  } = this
  return new LuPromise((onFulfilledNext, onRejectedNext) => {
    // 封装一个状态为Fulfilled的函数
    let fulfilled = value => {
      try {
        // 如果onFulfilled参数不是函数
        if (!isFunction(onFUlfilled)) {
          // 直接将之前Promise的成功值value作为下一个Promise的值,进行调用
          onFulfilledNext(value)
        } else {
          // 如果onFulfilled参数是函数,记录函数返回值
          let result = onFUlfilled(value)
          // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
          if (result instanceof LuPromise) {
            result.then(onFulfilledNext, onRejectedNext)
          } else {
            // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
            onFulfilledNext(result)
          }
        }
      } catch (error) {
        // 如果函数出错,返回的Promise对象的状态变为rejected,并执行reject函数
        onRejectedNext(error)
      }
    }
    //封装一个状态为Rejected的函数
    let rejected = error => {
      try {
        // 如果onRejected参数不是函数
        if (!isFunction(onRejected)) {
          // 直接将之前Promise的失败值error作为下一个Promise的值,进行调用
          onRejectedNext(error)
        } else {
          // 如果onRejected参数是函数,记录函数返回值
          let result = onRejected(error)
          // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
          if (result instanceof LuPromise) {
            result.then(onFulfilledNext, onRejectedNext)
          } else {
            // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
            onFulfilledNext(result)
          }
        }
      } catch (error) {
        // 如果函数出错,返回的Promise对象的状态变为rejected,并执行reject函数
        onRejectedNext(error)
      }
    }
    switch (_status) {
      // 当状态还是进行中时,把两个方法都加入到回调函数事件队列中
      case PENDING:
        this._fulfilledArray.push(fulfilled)
        this._rejectedArray.push(rejected)
        break
        // 当状态改变成Fulfilled时,直接触发fulfilled函数
      case FULFILLED:
        fulfilled(_value)
        break
        // 当状态改变成Rejected时,直接触发rejected函数
      case REJECTED:
        rejected(_value)
        break
    }
  })
}

这里添加了对onFUlfilled和onRejected是否是函数的判断,如果不是函数,就发生所谓的值穿透。

let promise1 = new LuPromise((resolve, reject) => {
  resolve('resolve穿透了')
})
promise2 = promise1.then('then的第一个参数不是函数了,要发生值穿透了')
promise2.then(res => {
  console.log(res)
}, err => {
  console.log(err) // 打印出:fail
})

打印结果
在这里插入图片描述

let promise1 = new LuPromise((resolve, reject) => {
  reject('reject穿透了')
})
promise2 = promise1.then(res => res, 'then的第二个参数不是函数了,要发生值穿透了')
promise2.then(res => {
  console.log(res)
}, err => {
  console.log(err) // 打印出:fail
})

打印结果:

在这里插入图片描述
好!第9点值穿透也完成了

总结

实现了最主要的LuPromise类和then方法,在下篇中,将补齐一些静态方法

这是到目前为止的所有代码

// 判断是否是函数
const isFunction = f => typeof f === 'function'
// 定义Promise的三种状态常量
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'



class LuPromise {
  constructor(handle) {
    // 如果参数不是函数
    if (!isFunction(handle)) {
      // 不是函数就抛出错误
      throw new Error('LuPromise必须接收函数类型的参数')
    }
    // 添加状态属性 [[promiseStatus]]
    this._status = PENDING
    // 添加Promise的值 [[promiseValue]]
    this._value = undefined
    // 添加成功回调函数事件队列
    this._fulfilledArray = []
    // 添加失败回调函数事件队列
    this._rejectedArray = []
    try {
      // 执行handle后,这两个函数也就相当于了内部函数 高阶函数
      handle(this._resolve.bind(this), this._reject.bind(this))
    } catch (error) {
      this._reject(error)
    }
  }

  _resolve(val) {
    // resolve
    // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
    if (this._status !== PENDING) return
    const run = () => {
      this._status = FULFILLED
      this._value = val
      let CallBack;
      // 获取成功队列中的第一个回调函数,执行
      while (CallBack = this._fulfilledArray.shift()) {
        CallBack(val)
      }
    }

    // 通过MutationObserver实现微任务
    let ob = new MutationObserver(run)
    ob.observe(document.body, {
      attributes: true
    })
    document.body.setAttribute("lu", Math.random())
  }



  _reject(err) {
    // reject
    // 先检测Promise的状态是否是PENDING,如果不是,就直接返回
    if (this._status !== PENDING) return
    // 依次执行失败队列中的函数,并清空队列
    const run = () => {
      this._status = REJECTED
      this._value = err
      let CallBack;
      // 获取失败队列中的第一个回调函数,执行
      while (CallBack = this._rejectedArray.shift()) {
        CallBack(err)
      }
    }
    // 通过MutationObserver实现微任务
    let ob = new MutationObserver(run)
    ob.observe(document.body, {
      attributes: true
    })
    document.body.setAttribute("lu", Math.random())
  }
  // then方法
  then(onFUlfilled, onRejected) {
    const {
      _value,
      _status
    } = this

    return new LuPromise((onFulfilledNext, onRejectedNext) => {
      // 封装一个状态为Fulfilled的函数
      let fulfilled = value => {
        try {
          // 如果onFulfilled参数不是函数
          if (!isFunction(onFUlfilled)) {
            // 直接将之前Promise的成功值value作为下一个Promise的值,进行调用
            onFulfilledNext(value)
          } else {
            // 如果onFulfilled参数是函数,记录函数返回值
            let result = onFUlfilled(value)
            // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
            if (result instanceof LuPromise) {
              result.then(onFulfilledNext, onRejectedNext)
            } else {
              // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
              onFulfilledNext(result)
            }
          }

        } catch (error) {
          // 如果函数出错,返回的Promise对象的状态变为rejected,并执行reject函数
          onRejectedNext(error)
        }
      }

      //封装一个状态为Rejected的函数
      let rejected = error => {
        try {
          // 如果onRejected参数不是函数
          if (!isFunction(onRejected)) {
            // 直接将之前Promise的失败值error作为下一个Promise的值,进行调用
            onRejectedNext(error)
          } else {
            // 如果onRejected参数是函数,记录函数返回值
            let result = onRejected(error)
            // 如果回调函数onFulfilled返回的是Promise对象,则必须等待其状态改变后在执行下一个then的回调
            if (result instanceof LuPromise) {
              result.then(onFulfilledNext, onRejectedNext)
            } else {
              // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
              onFulfilledNext(result)
            }
          }

        } catch (error) {
          // 如果函数出错,返回的Promise对象的状态变为rejected,并执行reject函数
          onRejectedNext(error)
        }
      }

      switch (_status) {
        // 当状态还是进行中时,把两个方法都加入到回调函数事件队列中
        case PENDING:
          this._fulfilledArray.push(fulfilled)
          this._rejectedArray.push(rejected)
          break
          // 当状态改变成Fulfilled时,直接触发fulfilled函数
        case FULFILLED:
          fulfilled(_value)
          break
          // 当状态改变成Rejected时,直接触发rejected函数
        case REJECTED:
          rejected(_value)
          break
      }
    })
  }
}

猜你喜欢

转载自blog.csdn.net/qq_46299172/article/details/107735886
今日推荐