带你了解 “老生常谈”的Promise的实现(一)

56 阅读1分钟

一、基础功能描述

  1. Promise 是一个类,执行类的时候需要传递一个函数,函数会被立即执行。

  2. Promise 中有三个状态:等待 pending 成功 fulfilled 失败 rejected

• pending -> fulfilled

• pending -> rejected

• 一旦状态修改后不能再更改

  1. resolve和reject函数是用来更改状态的

• resolve函数 将状态修改为 fulfilled

• reject函数 将状态修改为 rejected

  1. then内部做的事情:

• 如果状态成功调用成功的回调函数,如果失败调用失败的回调函数。

•能被所有实例对象调用到,也就是在原型对象上

  1. then 成功回调有一个参数,表示成功之后的值value。

then 失败回调有一个参数,表示失败后的原因reason。

二、代码实现

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MPromise {
  constructor(executor){
    executor(this.resolve, this.reject)
  }
  status = PENDING

  // 成功后的值
  value = undefined
  //失败后的原因
  reason = undefined


  // resolve 和 reject都是箭头函数。
  // 因为在使用的过程中,直接调用,this指向的是window或者undefined,要让它指向MPromise的实例对象,所以此时应该 使用箭头函数
  resolve = (value) => { // value成功后的值
    // 状态一旦修改后不能再更改
    if(this.status != PENDING) return
    this.status = FULFILLED
    this.value = value
  }

  reject = (reason) => { // reason失败后的原因
    // 状态一旦修改后不能再更改
    if(this.status != PENDING) return
    this.status = REJECTED
    this.reason = reason
  }

  then(successCallback, failCallback) {
    // 状态判断
    if(this.status == FULFILLED) {
      successCallback(this.value)
    } else if(this.status == REJECTED){
      failCallback(this.reason)
    }
  }
}


let pro = new MPromise((res, rej)=>{
  res('成功的值')
  rej('失败的原因')
})

pro.then(value=> {
  console.log(value)
}, reason=> {
  console.log(reason)
})

三、敬请期待 —— 系列二