手撕Promise源码


日拱一卒终有尽, 功不唐捐终入海

在这里插入图片描述


一、Promise 类核心逻辑实现


思路:

  1. Promise 就是一个类 =>
  2. 需要有一个立即执行的回调 =>
  3. 传递两个参数resolve和reject(函数) =>
  4. resolve和reject能够改变状态 =>
  5. Promise 有三个特有的状态,并且不能被再次修改 =>
  6. 提供链式调用的 then 方法 =>
  7. 传递两个参数,分别执行失败/成功回调 =>
  8. 成功需要传递成功的参数,失败需要传递失败的原因 =>
  9. 导出 myPromise

定义 myPromise 方法:

//实现 Promise 核心功能

// myPromise 存在三个独有的状态
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败

// 创建一个名为 myPromise 的类
class myPromise {
  // 通过构造函数 constructor 来接收这个执行器(executor)
  constructor(executor) { // 立即执行
    // 传入两个参数,因为是箭头函数接收,所以用 this.
    executor(this.resolve, this.reject)
  }

  // 设定初始状态
  status = PENDING
  // 成功之后的值
  value = undefined
  // 失败之后的原因
  reason = undefined

  resolve = (val) => {
    // 状态不可更改
    if (this.status !== PENDING) return
    // 改变状态 等待 => 成功
    this.status = FULFILLED
    // 保存成功之后的值
    this.value = val
  }

  reject = (val) => {
    // 状态不可更改
    if (this.status !== PENDING) return
    // 改变状态 等待 => 失败
    this.status = REJECTED
    // 保存失败之后的原因
    this.reason = val
  }

  // 定义 then 方法, 接收两个参数 - 成功回调/失败回调
  then(successCallBack, failCallBack) {
    // 判断状态
    if (this.status === FULFILLED) { // 调用成功回调
      // 传入成功的值
      successCallBack(this.value)
    } else if (this.status === REJECTED) { // 调用失败回调
      // 传入失败的原因
      failCallBack(this.reason)
    }
  }
}

// 导出
module.exports = myPromise

调用 myPromise:

// 调用 myPromise

const myPromise = require("./myPromise")

const promise = new myPromise((resolve, reject) => {
  resolve('成功')
  reject('失败')
})

promise.then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})
// => 成功

二、Promise 类中加入异步逻辑


调用 myPromise:

const myPromise = require("./02-myPromise")
const promise = new myPromise((resolve, reject) => {
  // resolve('成功')
  
  // 执行器中使用异步, resolve 方法会延迟执行(setTimeout 是宏任务, Promise 是微任务)
  setTimeout(() => {
    resolve('成功')
  }, 500)

  // reject('失败')
})

// then 方法会立即执行, 此时的 myPromise 中, status 状态是 pending 状态, 所以不会发生成功/失败回调
promise.then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})
// => 无打印结果

思路:

  1. 设置两个变量,初始值为 undefined
  2. 两个变量分别用来储存(then 方法中) pending 状态时的成功/失败回调
  3. 执行异步的 resolve/reject 时,判断变量是否存在
  4. 如果存在,则立即执行 成功/失败回调

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    executor(this.resolve, this.reject)
  }

  status = PENDING
  value = undefined
  reason = undefined
  // 成功之后回调
  successCallBack = undefined
  // 失败之后的回调
  failCallBack = undefined

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    // 如果成功的回调是否存在 如果存在 调用
    this.successCallBack && this.successCallBack(this.value)
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    // 如果失败的回调是否存在 如果存在 调用
    this.failCallBack && this.failCallBack(this.reason)
  }

  then(successCallBack, failCallBack) {
    if (this.status === FULFILLED) {
      successCallBack(this.value)
    } else if (this.status === REJECTED) {
      failCallBack(this.reason)
    } else { // 等待状态(异步)
      // 储存成功回调
      this.successCallBack = successCallBack
      // 储存失败回调
      this.failCallBack = failCallBack
    }
  }
}

module.exports = myPromise

三、实现 then 方法多次调用添加多个处理函数


调用 myPromise - 多个同步函数:

// 调用 myPromise

const myPromise = require("./03-myPromise")

const promise = new myPromise((resolve, reject) => {
   resolve('成功')
   reject('失败')
})

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

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

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

// => 成功 成功 成功

调用 myPromise - 多个异步步函数:

// 调用 myPromise

const myPromise = require("./03-myPromise")

const promise = new myPromise((resolve, reject) => {
  // resolve('成功')

  setTimeout(() => {
    resolve('成功')
  }, 500)

  // reject('失败')
})

// 上一节中:设置了两个变量分别用来储存(then 方法中) pending 状态时的成功/失败回调,但是只能存储一个 成功/失败的回调
// 所以导致多个异步函数只能返回一个异步结果
promise.then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})
promise.then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})
promise.then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})
// => 成功

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    executor(this.resolve, this.reject)
  }

  status = PENDING
  value = undefined
  reason = undefined
  // 成功之后回调(接收多个处理函数)
  successCallBack = []
  // 失败之后的回调(接收多个处理函数)
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    // 如果成功的回调是否存在 如果存在 调用
    // this.successCallBack && this.successCallBack(this.value)

    // while 循环 - 指定条件为真时循环执行代码块
    // shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值

    while (this.successCallBack.length) { // 立即执行
      this.successCallBack.shift()(this.value)
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    // 如果失败的回调是否存在 如果存在 调用
    // this.failCallBack && this.failCallBack(this.reason)

    while (this.successCallBack.length) { // 立即执行
      this.successCallBack.shift()(this.reason)
    }
  }

  then(successCallBack, failCallBack) {
    if (this.status === FULFILLED) {
      successCallBack(this.value)
    } else if (this.status === REJECTED) {
      failCallBack(this.reason)
    } else { // 等待状态(异步)
      // 可以储存多个 成功回调
      this.successCallBack.push(successCallBack)
      // 可以储存多个 失败回调
      this.failCallBack.push(failCallBack)
    }
  }
}

module.exports = myPromise

四、实现 then 方法的链式调用


调用 myPromise - 实现 then 方法多次链式调用:

// 调用 myPromise

const myPromise = require("./04-myPromise")

const promise = new myPromise((resolve, reject) => {
  resolve('成功')
  // reject('失败')
})

promise.then(value => {
    console.log(value)
    return 100
  })
  // then 方法链式调用
  .then(value => {
    console.log(value)
    // => Cannot read property 'then' of undefined(报错)
  })

思路:

then 方法链式调用的参数是上一个 then 方法返回的 全新 promise 对象

  1. 在 then 方法中创建一个 promise 对象,并传递出去
  2. 将(上一个)then 方法 的返回值传递给下一个 then 方法
  3. 判断(上一个)then 方法的返回值
  4. 如果是普通值,直接调用 resolve()方法
  5. 如果是 promise 对象,则根据结果选择调用 resolve() / reject() 方法

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    executor(this.resolve, this.reject)
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()(this.value)
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()(this.reason)
    }
  }

  then(successCallBack, failCallBack) {
    // 创建一个 promise 对象
    let promise2 = new myPromise((resolve, reject) => { // 传递一个 立即执行 的执行器
      if (this.status === FULFILLED) {
        // successCallBack(this.value)

        // 储存 (上一个)then 的返回值
        let x = successCallBack(this.value)
        // 将值传递给 下一个 then 方法的回调函数
        // resolve(x)

        // 引用公共方法(解析 promise) 
        resolvePromise(x, resolve, reject)
      } else if (this.status === REJECTED) {
        failCallBack(this.reason)
      } else {
        this.successCallBack.push(successCallBack)
        this.failCallBack.push(failCallBack)
      }
    })
    // 返回 promise 对象, 供下一个 then 方法调用
    return promise2
  }
}

// 创建公共方法(解析 Promise)
function resolvePromise(x, resolve, reject) {
  // 如果是 Promise 对象
  if (x instanceof myPromise) { // 调用Promise 对象的 then 方法


    // x.then(
    //   // 如果 promise 对象是成功的
    //   (value) => {
    //     resolve(value)
    //   },
    //   // 如果 promise 对象是失败的
    //   (reason) => {
    //     reject(reason)
    //   }
    // )

    // 简写 =>
    x.then(resolve, reject)

    // 如果是普通值
  } else { // 直接调用 resolve 方法
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - then 方法返回普通值Promise 对象

// 调用 myPromise

const myPromise = require("./04-myPromise")

const promise = new myPromise((resolve, reject) => {
  resolve('成功')
  // reject('失败')
})

// 创建一个 Promise 对象
function other () { // 返回一个 Promise 对象
  return new myPromise((resolve, reject) => { // 传入一个执行器
    resolve('other')
    // reject()
  })
}


promise.then(value => {
    console.log(value)
    // return 100

    // 返回 other 函数的调用
    return other()
  })
  // then 方法链式调用
  .then(value => {
    console.log(value)
    // => 成功  100
    // => 成功  other
  })

五、then 方法识别 返回Promise 本身


调用 Promise - 实现 then 方法返回 promise 对象本身:

  // 调试 (原生)promise
  
  const promise2 = new Promise((resolve, reject) => {
    resolve(100)
  })

  let p = promise2.then(function(value) { // 传递一个成功的回调函数
    console.log(value)
    // 返回 then 方法 返回的 promise 对象
    return p // 发生了 promise 的循环调用
    //  Chaining cycle detected for promise => 检测到promise的链接周期
  })

思路:

  1. 成功回调返回的 promise 对象和 then 方法返回的 promise 对象做比较
  2. 如果相同,执行失败回调,并返回失败的原因
  3. 将比较的判断转为异步执行,确保在 then 方法返回 Promise 对象后执行

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    executor(this.resolve, this.reject)
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()(this.value)
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()(this.reason)
    }
  }

  then(successCallBack, failCallBack) {
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => { // 异步执行,确保得到 promise2(then 方法返回的 promise 对象)
          let x = successCallBack(this.value)
          // 将 then 方法返回的 promise 对象传入
          resolvePromise(promise2, x, resolve, reject)
        }, 0)
      } else if (this.status === REJECTED) {
        failCallBack(this.reason)
      } else {
        this.successCallBack.push(successCallBack)
        this.failCallBack.push(failCallBack)
      }
    })
    return promise2
  }
}

// 接收 then 方法返回的 promise 对象
function resolvePromise(promise2, x, resolve, reject) {
  // 比较 `成功回调`返回的 promise 对象 和 `then 方法`返回的 promise 对象
  if(x === promise2) { // 如果相同
    // 执行失败回调
    return reject( // 返回失败的原因
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - 实现 then 方法返回 promise 对象本身:

// 调用 myPromise

const myPromise = require("./05-myPromise")

const promise = new myPromise((resolve, reject) => {
  resolve('成功')
  // reject('失败')
})

function other () {
  return new myPromise((resolve, reject) => {
    resolve('other')
    // reject()
  })
}

// 通过变量 p , 储存 then 方法返回的 promise 对象
let p = promise.then(value => {
    console.log(value)
    // 循环调用: 将 then 方法返回的 promise 对象, 进行返回
    return p
  })

  // 循环调用的错误会传递到下一个 then 方法的 失败回调函数当中
  p.then(value => {
    console.log(value)
  }, reason => { // 传递一个失败的回调函数
    // 获取报错信息内容
    console.log(reason)
    // => TypeError: Chaining cycle detected for promise #<Promise>
  })

六、捕获错误及 then 方法的补充

1. 捕获错误:

  • 在 promise 中,如果运行错误,需要在 then 方法回调中捕获错误的原因
  • 在 then 方法中,如果执行错误,需要在下一个 then 回调中捕获到错误的原因

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try { // 尝试运行
      executor(this.resolve, this.reject)
    } catch (error) { // 如果运行失败
      // 执行失败函数, 传递错误的原因
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()(this.value)
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()(this.reason)
    }
  }

  then(successCallBack, failCallBack) {
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try { // 执行
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) { // 如果执行失败
            // 指定 reject 方法, 传递失败的原因
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        failCallBack(this.reason)
      } else {
        this.successCallBack.push(successCallBack)
        this.failCallBack.push(failCallBack)
      }
    })
    return promise2
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 Promise - 实现 promisethen 方法 执行失败后抛出错误原因:

// 调用 myPromise

const myPromise = require("./05-myPromise")

const promise = new myPromise((resolve, reject) => {
  // 主动抛出错误
  // throw new Error('executer error')

  resolve('成功')
  // reject('失败')
})

promise.then(value => {
  throw new Error('then error')
  console.log(value)
}, reason => {
  console.log(reason) // 捕获错误
  // => Error: executer error
})
  .then(value => {
    console.log(value)
  }, reason => { // 捕获错误
    console.log(reason.message)
    // => Error: then error
  })

2. then 方法的补充

  • 完善 then方法 的失败回调
  • 完善then 方法 的异步回调

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      // this.successCallBack.shift()(this.value)

      // 不需要传值, 立即执行
      this.successCallBack.shift()()
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      // this.successCallBack.shift()(this.reason)

      // 不需要传值, 立即执行
      this.successCallBack.shift()()
    }
  }

  then(successCallBack, failCallBack) {
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        // failCallBack(this.reason)

        // 同成功回调, 实现异步/多次链式调用/识别返回 promise 对象本身/执行失败后抛出错误原因
        setTimeout(() => {
          try {
            let x = failCallBack(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else {
        // this.successCallBack.push(successCallBack)

        // push 整个函数,不然内部无法判断执行是否成功
        this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = successCallBack(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })


        // this.failCallBack.push(failCallBack)

        // push 整个函数,不然内部无法判断执行是否成功
        this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = failCallBack(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
      }
    })
    return promise2
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - 实现 then 方法失败回调 / 异步:

// 调用 myPromise

const myPromise = require("./06.2-myPromise")

const promise = new myPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功')
  }, 1000)
  // reject('失败')
})

promise.then(value => {
  console.log(value)
  return 10
}, reason => {
  console.log(reason)
  return 20
})
  .then(value => {
    console.log(value)
    // => 成功 10
  }, reason => {
    // console.log(reason)
    // => 失败 20
  })

七、将 then 方法的参数变为可选参数

调用 Promise - 实现 then 方法不传参:

  // 调试 promise(原生)
  
  const promise2 = new Promise((resolve, reject) => {
    resolve(100)
  })

promise2
  .then()
  .then()
  .then(value => console.log(value))
  // => 100

  // then 方法的参数是非必须的
  // 如果 then 方法未接收到参数, 则会依次向后传递, 直到传递给有回调函数的 then 方法

思路:

  1. 监听 then 方法的 成功 / 失败 回调 是否存在参数
  2. 如果存在, 就用起自身
  3. 如果不存在,则给 then 方法插入参数(成功的值 / 失败的原因),并向后传递

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  then(successCallBack, failCallBack) { // 判断 successCallBack failCallBack 是否存在
    // 如果存在, 就用 then 的成功回调 自身
    // 如果不存在, 就插入一个形参 value(成功的值), 并将 value 返回出去(向后传递)
    successCallBack = successCallBack ? successCallBack : value => value

    // 如果存在, 就用 then 的失败回调 自身
    // 如果不存在, 就插入一个形参  reason(错误的原因), 并将  reason 返回出去(向后传递)

    // failCallBack = failCallBack ? failCallBack : reason => { //  抛出错误
    //   throw reason
    // }
    failCallBack = failCallBack ? failCallBack : reason => reason //  抛出错误
    
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallBack(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else {
        this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = successCallBack(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = failCallBack(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
      }
    })
    return promise2
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - 实现 then 方法参数为空:

// 调用 myPromise

const myPromise = require("./07-myPromise")

const promise = new myPromise((resolve, reject) => {
  // resolve('成功')
  reject('失败')
})

promise
  .then()
  .then()
  .then(value => { // 执行回调函数
    console.log(value)
    // => 成功
  }, reason => { // 执行失败回调
    console.log(reason)
    // => 失败
  })

八、Promise.all 方法的实现

调用 Promise - 实现 Promise.all 方法:

// 调用 promise

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('1')
  }, 1000)
  // reject('失败')
})

const p2 = new Promise((resolve, reject) => {
  resolve('2')
})

Promise.all(['a', 'b', p1, p2, 'c'])
// Promise.all 传入的是一个数组,并且参数可以是对象,也可以是普通值
// Promise.all 返回的也是一个 Promise 对象, 所以可以使用 then 方法进行链式调用
.then(value => { // 全部执行成功, 才能成功
  console.log(value)
  // => [ 'a', 'b', '1', '2', 'c' ]
  // 得到的结果的顺序 也一定会是 传入的顺序(上面 p2 应该是先于 p1 执行)
  }, reason => { // 有一个失败, 即失败
    console.log(reason)
  })

思路:

  1. 创建静态方法 all
  2. 对 all 方法接收的参数数组做循环
  3. 通过参数是普通值,直接返回;如果是Promise 对象,将执行的结果返回
  4. 返回的顺序需要和执行的顺序相同(返回数组的脚标)
  5. 有一个执行失败,直接执行失败回调
  6. 循环时无法等待异步执行,处理异步执行问题

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  then(successCallBack, failCallBack) {
    successCallBack = successCallBack ? successCallBack : value => value
    failCallBack = failCallBack ? failCallBack : reason => reason
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallBack(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else {
        this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = successCallBack(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = failCallBack(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
      }
    })
    return promise2
  }

  // 声明一个静态方法 all, 接收数组作为参数
  static all(array) {
    // 定义结果数组
    let result = []

    // 定义一个变量,记录调用 addData (处理传递参数)的次数
    let index = 0

    // 返回一个 promise 对象, 传入执行器
    return new myPromise((resolve, reject) => {
      // 定义一个方法, 将值传递数组中
      function addData(key, value) {
        result[key] = value
        index++
        if (index === array.length) { // 传入参数的执行次数 === 添加值到结果数组的次数
          // 执行 resolve 方法,将 结果数组 传递回去
          resolve(result)
        }
      }

      // 循环数组
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        // 类型判断
        if (current instanceof myPromise) { // Promise 对象
          current.then( // 执行 current 的 Promise 对象
            // 传入成功回调,  将执行的结果添加到 结果数组中
            value => addData(i, value),
            // 传入失败回调, 如果有一个失败, 直接调用失败的方法, 并且传递失败的原因
            reason => reject(reason)
          )
        } else { // 普通值
          // 直接放到结果数组当中
          addData(i, array[i])
        }
      }
      // 循环结束后, 执行 resolve 方法, 并传递结果数组
      resolve(result)
    })
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - all 方法:

// 调用 myPromise

const myPromise = require("./08-myPromise")

const p1 = new myPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('p1')
  }, 2000)
  // reject('失败')
})

const p2 = new myPromise((resolve, reject) => {
  resolve('p2')
})


Promise.all(['a', 'b', p1, p2, 'c'])
  .then(value => {
    console.log(value)
    // => [ 'a', 'b', 'p1', 'p2', 'c' ]
  }, reason => {
    console.log(reason)
  })

九、Promise.resolve 方法

调用 Promise - 实现 Promise.resolve 方法:

// 调用 promise

const p = new Promise((resolve, reject) => {
  resolve('hello')
  // reject('失败')
})

Promise.resolve(10)
  // Promise.resolve 的参数如果是普通值, 会将传入的参数 包裹在 Promise 对象中来返回, 所以能够被 then 方法链式调用
  .then(value => {
    console.log(value)
    // => 10
  }, reason => {
    console.log(reason)
  })
  
  Promise.resolve(p)
    // Promise.resolve 的参数如果是Promise 对象, 会将 其 直接返回
    .then(value => {
      console.log(value)
      // => hello
    }, reason => {
      console.log(reason)
    })

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  then(successCallBack, failCallBack) {
    successCallBack = successCallBack ? successCallBack : value => value
    failCallBack = failCallBack ? failCallBack : reason => reason
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallBack(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else {
        this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = successCallBack(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = failCallBack(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
      }
    })
    return promise2
  }

  static all(array) {
    let result = []
    let index = 0
    return new myPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof myPromise) {
          current.then(
            value => addData(i, value),
            reason => reject(reason)
          )
        } else {
          addData(i, array[i])
        }
      }
      resolve(result)
    })
  }

  // 创建 resolve 的静态方法
  static resolve(value) {
    // 判断是否是 Promise 的实例对象
    if (value instanceof myPromise) { // 如果参数是对象
      // 直接返回 Promise 对象
      return value
    } else { // 如果是普通值
      // 创建一个 promise 对象, 传入一个执行器
      return new myPromise(resolve =>{ // 将 value 包裹起来
        resolve(value)
      })
    }
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - resolve 方法:

// 调用 myPromise

const myPromise = require("./09-myPromise")

const p1 = new myPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('hello')
    // reject('失败')
  }, 1000)
})


Promise.resolve(100)
  .then(value => {
    console.log(value)
    // => 100
  }, reason => {
    console.log(reason)
  })

Promise.resolve(p1)
  .then(value => {
    console.log(value)
    // => hello
  }, reason => {
    console.log(reason)
  })

十、Promise.finally 方法

  • 无论 finally 方法成功还是失败,Promise.finally 方法都会被执行
  • finally 可以被 then 方法获取到最终返回的结果

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  then(successCallBack, failCallBack) {
    successCallBack = successCallBack ? successCallBack : value => value
    failCallBack = failCallBack ? failCallBack : reason => reason
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallBack(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else {
        this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = successCallBack(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = failCallBack(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
      }
    })
    return promise2
  }

  // 创建一个 finally 方法, 并传入一个回调函数
  finally(callback) {
    // 通过 then 方法获取当前 Promise 的状态
    // 返回 then 方法作为回调的 Promise 对象
    return this.then(
      // 成功回调
      value => {
        // callback()
        // // 向下一个 then 方法传递成功的值
        // return value

        // 通过 resolve 方法, 等待 callback 执行完成后再返回 成功的值(包裹成 Promise 对象)
        return myPromise.resolve(callback())
          .then(() => {
            return value
          })
      },
      // 失败回调
      reason => {
        // callback()
        // // 向下一个 then 方法传递失败的原因
        // // throw reason
        // return reason
        // 通过 resolve 方法, 等待 callback 执行完成后再返回 失败的原因(包裹成 Promise 对象)
        return myPromise.resolve(callback())
          .then(() => {
            return reason
          })
      }
    )
  }

  static all(array) {
    let result = []
    let index = 0
    return new myPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof myPromise) {
          current.then(
            value => addData(i, value),
            reason => reject(reason)
          )
        } else {
          addData(i, array[i])
        }
      }
      resolve(result)
    })
  }

  static resolve(value) {
    if (value instanceof myPromise) {
      return value
    } else {
      return new myPromise(resolve => {
        resolve(value)
      })
    }
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - finally 方法:

// 调用 myPromise

const myPromise = require("./10-myPromise")

const p1 = new myPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功')
    // reject('失败')
  }, 1000)
})

// 无论成功失败, 都会执行后面的内容
p1.finally(()=> {
  console.log('finally')
  // => finally
})

  .then(value => {
    console.log(value)
    // => 成功
  }, reason => {
    console.log(reason)
  })


十一、Promise.catch 方法

  • 如果 then 方法中不执行失败回调,catch 就会捕获失败回调,从而将失败的原因传入 catch 方法的回调函数当中
  • 只需要在 catch 方法中,执行 then 方法,在成功函数传入 undefined,失败的函数传入 失败回调

定义 myPromise 方法:

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

class myPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (error) {
      this.reject(error)
    }
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallBack = []
  failCallBack = []

  resolve = (val) => {
    if (this.status !== PENDING) return
    this.status = FULFILLED
    this.value = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  reject = (val) => {
    if (this.status !== PENDING) return
    this.status = REJECTED
    this.reason = val
    while (this.successCallBack.length) {
      this.successCallBack.shift()()
    }
  }

  then(successCallBack, failCallBack) {
    successCallBack = successCallBack ? successCallBack : value => value
    failCallBack = failCallBack ? failCallBack : reason => reason
    let promise2 = new myPromise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallBack(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallBack(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (error) {
            reject(error)
          }
        }, 0)
      } else {
        this.successCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = successCallBack(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
        this.failCallBack.push(() => {
          setTimeout(() => {
            try {
              let x = failCallBack(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (error) {
              reject(error)
            }
          }, 0)
        })
      }
    })
    return promise2
  }

  finally(callback) {
    return this.then(
      value => {
        return myPromise.resolve(callback())
          .then(() => {
            return value
          })
      },
      reason => {
        return myPromise.resolve(callback())
          .then(() => {
            return reason
          })
      }
    )
  }

  // 创建一个 catch 方法, 只需要传入一个失败回调
  catch(failCallBack) {
    // 成功的函数不传, 失败的函数传入失败的回调
    return this.then(undefined, failCallBack)
  }


  static all(array) {
    let result = []
    let index = 0
    return new myPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof myPromise) {
          current.then(
            value => addData(i, value),
            reason => reject(reason)
          )
        } else {
          addData(i, array[i])
        }
      }
      resolve(result)
    })
  }

  static resolve(value) {
    if (value instanceof myPromise) {
      return value
    } else {
      return new myPromise(resolve => {
        resolve(value)
      })
    }
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(
      new TypeError('Chaining cycle detected for promise #<Promise>')
    )
  }
  if (x instanceof myPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}

module.exports = myPromise

调用 myPromise - catch 方法:

// 调用 myPromise

const myPromise = require("./11-myPromise")

const p1 = new myPromise((resolve, reject) => {
    // resolve('成功')
    reject('失败')
})

p1
  .then(value => {
    console.log(value)
  })
  .catch(reason => console.log(reason))
  // => 失败


下一篇:ECMAScript 新特性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后海 0_o

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值