深度剖析:手寫一個Promise源碼

目錄

  • 一、Promise核心邏輯實現(xiàn)
  • 二、在 Promise 類中加入異步邏輯
  • 三、實現(xiàn) then 方法多次調(diào)用添加多個處理函數(shù)
  • 四、實現(xiàn)then方法的鏈式調(diào)用
  • 五、then方法鏈式調(diào)用識別 Promise 對象自返回
  • 六、捕獲錯誤及 then 鏈式調(diào)用其他狀態(tài)代碼補充
      1. 捕獲執(zhí)行器的錯誤
      1. then執(zhí)行的時候報錯捕獲
      1. 錯誤之后的鏈式調(diào)用
      1. 異步狀態(tài)下鏈式調(diào)用
  • 七、將then方法的參數(shù)變成可選參數(shù)
  • 八、promise.all方法的實現(xiàn)
  • 九、Promise.resolve方法的實現(xiàn)
  • 十、finally 方法的實現(xiàn)
  • 十一、catch方法的實現(xiàn)
  • Promise全部代碼整合

這里只是對Promise源碼的實現(xiàn)做一個剖析,如果想對Promise整體有個了解,

請看 ES6(十一)—— Promise(更優(yōu)的異步編程解決方案)

一、Promise核心邏輯實現(xiàn)

首先分析其原理

  1. promise就是一個類

    在執(zhí)行類的時候需要傳遞一個執(zhí)行器進去,執(zhí)行器會立即執(zhí)行
  2. Promise中有三種狀態(tài),分別為成功-fulfilled 失敗-rejected 等待-pending

    pending -> fulfilled

    pending -> rejected

    一旦狀態(tài)確定就不可更改
  3. resolvereject函數(shù)是用來更改狀態(tài)的

    resolve:fulfilled

    reject:rejected
  4. then方法內(nèi)部做的事情就是判斷狀態(tài)
    如果狀態(tài)是成功,調(diào)用成功回調(diào)函數(shù)

    如果狀態(tài)是失敗,就調(diào)用失敗回調(diào)函數(shù)

    then方法是被定義在原型對象中的
  5. then成功回調(diào)有一個參數(shù),表示成功之后的值;then失敗回調(diào)有一個參數(shù),表示失敗后的原因

<PS:本文myPromise.js是源碼文件,promise.js是使用promise文件>

// myPromise.js
// 定義成常量是為了復用且代碼有提示
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失敗
// 定義一個構(gòu)造函數(shù)
class MyPromise {
  constructor (exector) {
    // exector是一個執(zhí)行器,進入會立即執(zhí)行,并傳入resolve和reject方法
    exector(this.resolve, this.reject)
  }

  // 實例對象的一個屬性,初始為等待
  status = PENDING
  // 成功之后的值
  value = undefined
  // 失敗之后的原因
  reason = undefined

  // resolve和reject為什么要用箭頭函數(shù)?
  // 如果直接調(diào)用的話,普通函數(shù)this指向的是window或者undefined
  // 用箭頭函數(shù)就可以讓this指向當前實例對象
  resolve = value => {
    // 判斷狀態(tài)是不是等待,阻止程序向下執(zhí)行
    if(this.status !== PENDING) return
    // 將狀態(tài)改成成功
    this.status = FULFILLED
    // 保存成功之后的值
    this.value = value
  }

  reject = reason => {
    if(this.status !== PENDING) return
    // 將狀態(tài)改為失敗
    this.status = REJECTED
    // 保存失敗之后的原因
    this.reason = reason
  }

  then (successCallback, failCallback) {
    //判斷狀態(tài)
    if(this.status === FULFILLED) {
      // 調(diào)用成功回調(diào),并且把值返回
      successCallback(this.value)
    } else if (this.status === REJECTED) {
      // 調(diào)用失敗回調(diào),并且把原因返回
      failCallback(this.reason)
    }
  }
}

module.exports = MyPromise
//promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
   resolve('success')
   reject('err')
 })

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

二、在 Promise 類中加入異步邏輯

上面是沒有經(jīng)過異步處理的,如果有異步邏輯加進來,會有一些問題

//promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  // 主線程代碼立即執(zhí)行,setTimeout是異步代碼,then會馬上執(zhí)行,
  // 這個時候判斷promise狀態(tài),狀態(tài)是pending,然而之前并沒有判斷等待這個狀態(tài)
  setTimeout(() => {
    resolve('success')
  }, 2000); 
 })

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

下面修改這個代碼

// myPromise.js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    exector(this.resolve, this.reject)
  }


  status = PENDING
  value = undefined
  reason = undefined
  // 定義一個成功回調(diào)參數(shù)
  successCallback = undefined
  // 定義一個失敗回調(diào)參數(shù)
  failCallback = undefined

  resolve = value => {
    if(this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    // 判斷成功回調(diào)是否存在,如果存在就調(diào)用
    this.successCallback && this.successCallback(this.value)
  }

  reject = reason => {
    if(this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // 判斷失敗回調(diào)是否存在,如果存在就調(diào)用
    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 {
      // 等待
      // 因為并不知道狀態(tài),所以將成功回調(diào)和失敗回調(diào)存儲起來
      // 等到執(zhí)行成功失敗函數(shù)的時候再傳遞
      this.successCallback = successCallback
      this.failCallback = failCallback
    }
  }
}

module.exports = MyPromise

三、實現(xiàn) then 方法多次調(diào)用添加多個處理函數(shù)

promisethen方法是可以被多次調(diào)用的。

這里如果有三個then的調(diào)用,

  • 如果是同步回調(diào),那么直接返回當前的值就行;
  • 如果是異步回調(diào),那么保存的成功失敗的回調(diào),需要用不同的值保存,因為都互不相同。

之前的代碼需要改進。

//promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  }, 2000); 
 })

 promise.then(value => {
   console.log(1)
   console.log('resolve', value)
 })
 
 promise.then(value => {
  console.log(2)
  console.log('resolve', value)
})

promise.then(value => {
  console.log(3)
  console.log('resolve', value)
})

保存到數(shù)組中,最后統(tǒng)一執(zhí)行

// myPromise.js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    exector(this.resolve, this.reject)
  }


  status = PENDING
  value = undefined
  reason = undefined
  // 定義一個成功回調(diào)參數(shù),初始化一個空數(shù)組
  successCallback = []
  // 定義一個失敗回調(diào)參數(shù),初始化一個空數(shù)組
  failCallback = []

  resolve = value => {
    if(this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    // 判斷成功回調(diào)是否存在,如果存在就調(diào)用
    // 循環(huán)回調(diào)數(shù)組. 把數(shù)組前面的方法彈出來并且直接調(diào)用
    // shift方法是在數(shù)組中刪除值,每執(zhí)行一個就刪除一個,最終變?yōu)?
    while(this.successCallback.length) this.successCallback.shift()(this.value)
  }

  reject = reason => {
    if(this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // 判斷失敗回調(diào)是否存在,如果存在就調(diào)用
    // 循環(huán)回調(diào)數(shù)組. 把數(shù)組前面的方法彈出來并且直接調(diào)用
    while(this.failCallback.length) this.failCallback.shift()(this.reason)
  }

  then (successCallback, failCallback) {
    if(this.status === FULFILLED) {
      successCallback(this.value)
    } else if (this.status === REJECTED) {
      failCallback(this.reason)
    } else {
      // 等待
      // 將成功回調(diào)和失敗回調(diào)都保存在數(shù)組中
      this.successCallback.push(successCallback)
      this.failCallback.push(failCallback)
    }
  }
}

module.exports = MyPromise

四、實現(xiàn)then方法的鏈式調(diào)用

  • then方法要鏈式調(diào)用那么就需要返回一個promise對象,

  • then方法的return返回值作為下一個then方法的參數(shù)

  • then方法還一個return一個promise對象,那么如果是一個promise對象,那么就需要判斷它的狀態(tài)

// promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
// 目前這里只處理同步的問題
    resolve('success')
})

function other () {
   return new MyPromise((resolve, reject) =>{
        resolve('other')
   })
}
promise.then(value => {
   console.log(1)
   console.log('resolve', value)
   return other()
}).then(value => {
  console.log(2)
  console.log('resolve', value)
})
// myPromise.js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    exector(this.resolve, this.reject)
  }

  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []

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

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

  then (successCallback, failCallback) {
    // then方法返回第一個promise對象
    let promise2 = new Promise((resolve, reject) => {
      if(this.status === FULFILLED) {
        // x是上一個promise回調(diào)函數(shù)的return返回值
        // 判斷 x 的值時普通值還是promise對象
        // 如果是普通紙 直接調(diào)用resolve
        // 如果是promise對象 查看promise對象返回的結(jié)果
        // 再根據(jù)promise對象返回的結(jié)果 決定調(diào)用resolve還是reject
        let x = successCallback(this.value)
        resolvePromise(x, resolve, reject)
      } else if (this.status === REJECTED) {
        failCallback(this.reason)
      } else {
        this.successCallback.push(successCallback)
        this.failCallback.push(failCallback)
      }
    });
    return promise2
  }
}

function resolvePromise(x, resolve, reject) {
  // 判斷x是不是其實例對象
  if(x instanceof MyPromise) {
    // promise 對象
    // x.then(value => resolve(value), reason => reject(reason))
    // 簡化之后
    x.then(resolve, reject)
  } else{
    // 普通值
    resolve(x)
  }
}

module.exports = MyPromise

五、then方法鏈式調(diào)用識別 Promise 對象自返回

如果then方法返回的是自己的promise對象,則會發(fā)生promise的嵌套,這個時候程序會報錯

var promise = new Promise((resolve, reject) => {
  resolve(100)
})
var p1 = promise.then(value => {
  console.log(value)
  return p1
})

// 100
// Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>

所以為了避免這種情況,我們需要改造一下then方法

// myPromise.js
const { rejects } = require("assert")

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    exector(this.resolve, this.reject)
  }


  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []

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

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

  then (successCallback, failCallback) {
    let promise2 = new Promise((resolve, reject) => {
      if(this.status === FULFILLED) {
        // 因為new Promise需要執(zhí)行完成之后才有promise2,同步代碼中沒有pormise2,
        // 所以這部分代碼需要異步執(zhí)行
        setTimeout(() => {
          let x = successCallback(this.value)
          //需要判斷then之后return的promise對象和原來的是不是一樣的,
          //判斷x和promise2是否相等,所以給resolvePromise中傳遞promise2過去
          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
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  // 如果相等了,說明return的是自己,拋出類型錯誤并返回
  if (promise2 === x) {
    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.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
    resolve('success')
})
 
// 這個時候?qū)romise定義一個p1,然后返回的時候返回p1這個promise
let p1 = promise.then(value => {
   console.log(1)
   console.log('resolve', value)
   return p1
})
 
// 運行的時候會走reject
p1.then(value => {
  console.log(2)
  console.log('resolve', value)
}, reason => {
  console.log(3)
  console.log(reason.message)
})

// 1
// resolve success
// 3
// Chaining cycle detected for promise #<Promise>

六、捕獲錯誤及 then 鏈式調(diào)用其他狀態(tài)代碼補充

目前我們在Promise類中沒有進行任何處理,所以我們需要捕獲和處理錯誤。

1. 捕獲執(zhí)行器的錯誤

捕獲執(zhí)行器中的代碼,如果執(zhí)行器中有代碼錯誤,那么promise的狀態(tài)要弄成錯誤狀態(tài)

// myPromise.js
constructor (exector) {
    // 捕獲錯誤,如果有錯誤就執(zhí)行reject
    try {
        exector(this.resolve, this.reject)
    } catch (e) {
        this.reject(e)
    }
}
// promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
    // resolve('success')
    throw new Error('執(zhí)行器錯誤')
})
 
promise.then(value => {
  console.log(1)
  console.log('resolve', value)
}, reason => {
  console.log(2)
  console.log(reason.message)
})

//2
//執(zhí)行器錯誤

2. then執(zhí)行的時候報錯捕獲

// myPromise.js
then (successCallback, failCallback) {
    let promise2 = new Promise((resolve, reject) => {
        if(this.status === FULFILLED) {
            setTimeout(() => {
                // 如果回調(diào)中報錯的話就執(zhí)行reject
                try {
                    let x = successCallback(this.value)
                    resolvePromise(promise2, x, resolve, reject)
                } catch (e) {
                    reject(e)
                }
            }, 0);
        } else if (this.status === REJECTED) {
            failCallback(this.reason)
        } else {
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    });
    return promise2
}
// promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
    resolve('success')
    // throw new Error('執(zhí)行器錯誤')
 })
 
// 第一個then方法中的錯誤要在第二個then方法中捕獲到
promise.then(value => {
  console.log(1)
  console.log('resolve', value)
  throw new Error('then error')
}, reason => {
  console.log(2)
  console.log(reason.message)
}).then(value => {
  console.log(3)
  console.log(value);
}, reason => {
  console.log(4)
  console.log(reason.message)
})

// 1
// resolve success
// 4
// then error

3. 錯誤之后的鏈式調(diào)用

// myPromise.js
then (successCallback, failCallback) {
    let promise2 = new Promise((resolve, reject) => {
        if(this.status === FULFILLED) {
            setTimeout(() => {
                try {
                    let x = successCallback(this.value)
                    resolvePromise(promise2, x, resolve, reject)
                } catch (e) {
                    reject(e)
                }
            }, 0)
        // 在狀態(tài)是reject的時候?qū)Ψ祷氐膒romise進行處理
        } else if (this.status === REJECTED) {
            setTimeout(() => {
                // 如果回調(diào)中報錯的話就執(zhí)行reject
                try {
                    let x = failCallback(this.reason)
                    resolvePromise(promise2, x, resolve, reject)
                } catch (e) {
                    reject(e)
                }
            }, 0)
        } else {
            this.successCallback.push(successCallback)
            this.failCallback.push(failCallback)
        }
    });
    return promise2
}
//promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
    // resolve('success')
    throw new Error('執(zhí)行器錯誤')
 })
 
 // 第一個then方法中的錯誤要在第二個then方法中捕獲到
 promise.then(value => {
  console.log(1)
  console.log('resolve', value)
}, reason => {
  console.log(2)
  console.log(reason.message)
  return 100
}).then(value => {
  console.log(3)
  console.log(value);
}, reason => {
  console.log(4)
  console.log(reason.message)
})

// 2
// 執(zhí)行器錯誤
// 3
// 100

4. 異步狀態(tài)下鏈式調(diào)用

還是要處理一下如果promise里面有異步的時候,then的鏈式調(diào)用的問題。

// myPromise.js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    // 捕獲錯誤,如果有錯誤就執(zhí)行reject
    try {
      exector(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }


  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []

  resolve = value => {
    if(this.status !== PENDING) return
    this.status = FULFILLED
    this.value = value
    // 異步回調(diào)傳值
    // 調(diào)用的時候不需要傳值,因為下面push到里面的時候已經(jīng)處理好了
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if(this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // 異步回調(diào)傳值
    // 調(diào)用的時候不需要傳值,因為下面push到里面的時候已經(jīng)處理好了
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    let promise2 = new Promise((resolve, reject) => {
      if(this.status === FULFILLED) {
        setTimeout(() => {
          // 如果回調(diào)中報錯的話就執(zhí)行reject
          try {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          // 如果回調(diào)中報錯的話就執(zhí)行reject
          try {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        // 處理異步的成功錯誤情況
        this.successCallback.push(() => {
          setTimeout(() => {
            // 如果回調(diào)中報錯的話就執(zhí)行reject
            try {
              let x = successCallback(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            // 如果回調(diào)中報錯的話就執(zhí)行reject
            try {
              let x = failCallback(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    });
    return promise2
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    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.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  // 一個異步方法
  setTimeout(() =>{
    resolve('succ')
  },2000)
})
 
 promise.then(value => {
  console.log(1)
  console.log('resolve', value)
  return 'aaa'
}, reason => {
  console.log(2)
  console.log(reason.message)
  return 100
}).then(value => {
  console.log(3)
  console.log(value);
}, reason => {
  console.log(4)
  console.log(reason.message)
})

// 1
// resolve succ
// 3
// aaa

七、將then方法的參數(shù)變成可選參數(shù)

then方法的兩個參數(shù)都是可選參數(shù),我們可以不傳參數(shù)。
下面的參數(shù)可以傳遞到最后進行返回

var promise = new Promise((resolve, reject) => {
      resolve(100)
    })
    promise
      .then()
      .then()
      .then()
      .then(value => console.log(value))
// 在控制臺最后一個then中輸出了100

// 這個相當于
promise
  .then(value => value)
  .then(value => value)
  .then(value => value)
  .then(value => console.log(value))

所以我們修改一下then方法

// myPromise.js
then (successCallback, failCallback) {
    // 這里進行判斷,如果有回調(diào)就選擇回調(diào),如果沒有回調(diào)就傳一個函數(shù),把參數(shù)傳遞
    successCallback = successCallback ? successCallback : value => value
    // 錯誤函數(shù)也是進行賦值,把錯誤信息拋出
    failCallback = failCallback ? failCallback : reason => {throw reason}
    let promise2 = new Promise((resolve, reject) => {
        ...
    })
    ...
}


// 簡化也可以這樣寫
then (successCallback = value => value, failCallback = reason => {throw reason}) {
    ···
}

resolve之后

// promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  resolve('succ')
})
 
promise.then().then().then(value => console.log(value))

// succ

reject之后

// promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  reject('err')
})
 
 promise.then().then().then(value => console.log(value), reason => console.log(reason))

// err

八、promise.all方法的實現(xiàn)

promise.all方法是解決異步并發(fā)問題的

// 如果p1是兩秒之后執(zhí)行的,p2是立即執(zhí)行的,那么根據(jù)正常的是p2在p1的前面。
// 如果我們在all中指定了執(zhí)行順序,那么會根據(jù)我們傳遞的順序進行執(zhí)行。
function p1 () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('p2')
    },0)
  })
}

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

分析一下:

  • all方法接收一個數(shù)組,數(shù)組中可以是普通值也可以是promise對象
  • 數(shù)組中值得順序一定是我們得到的結(jié)果的順序
  • promise返回值也是一個promise對象,可以調(diào)用then方法
  • 如果數(shù)組中所有值是成功的,那么then里面就是成功回調(diào),如果有一個值是失敗的,那么then里面就是失敗的
  • 使用all方法是用類直接調(diào)用,那么all一定是一個靜態(tài)方法
//myPromise.js
static all (array) {
    //  結(jié)果數(shù)組
    let result = []
    // 計數(shù)器
    let index = 0
    return new Promise((resolve, reject) => {
      let addData = (key, value) => {
        result[key] = value
        index ++
        // 如果計數(shù)器和數(shù)組長度相同,那說明所有的元素都執(zhí)行完畢了,就可以輸出了
        if(index === array.length) {
          resolve(result)
        }
      }
      // 對傳遞的數(shù)組進行遍歷
      for (let i = 0; i < array.lengt; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          // promise對象就執(zhí)行then,如果是resolve就把值添加到數(shù)組中去,如果是錯誤就執(zhí)行reject返回
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          // 普通值就加到對應的數(shù)組中去
          addData(i, array[i])
        }
      }
    })
}
// promise.js
const MyPromise = require('./myPromise')
function p1 () {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve('p2')
    },0)
  })
}

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

九、Promise.resolve方法的實現(xiàn)

  • 如果參數(shù)就是一個promise對象,直接返回,如果是一個值,那么需要生成一個promise對象,把值進行返回
  • Promise類的一個靜態(tài)方法
// myPromise.js
static resolve (value) {
    // 如果是promise對象,就直接返回
    if(value instanceof MyPromise) return value
    // 如果是值就返回一個promise對象,并返回值
    return new MyPromise(resolve => resolve(value))
}
// promise.js
const MyPromise = require('./myPromise')
function p1 () {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve('p1')
    }, 2000)
  })
}


Promise.resolve(100).then(value => console.log(value))
Promise.resolve(p1()).then(value => console.log(value))
// 100
// 2s 之后輸出 p1

十、finally 方法的實現(xiàn)

  • 無論當前最終狀態(tài)是成功還是失敗,finally都會執(zhí)行
  • 我們可以在finally方法之后調(diào)用then方法拿到結(jié)果
  • 這個函數(shù)是在原型對象上用的
// myPromise.js
finally (callback) {
    // 如何拿到當前的promise的狀態(tài),使用then方法,而且不管怎樣都返回callback
    // 而且then方法就是返回一個promise對象,那么我們直接返回then方法調(diào)用之后的結(jié)果即可
    // 我們需要在回調(diào)之后拿到成功的回調(diào),所以需要把value也return
    // 失敗的回調(diào)也拋出原因
    // 如果callback是一個異步的promise對象,我們還需要等待其執(zhí)行完畢,所以需要用到靜態(tài)方法resolve
    return this.then(value => {
      // 把callback調(diào)用之后返回的promise傳遞過去,并且執(zhí)行promise,且在成功之后返回value
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      // 失敗之后調(diào)用的then方法,然后把失敗的原因返回出去。
      return MyPromise.resolve(callback()).then(() => { throw reason })
    })
}
// promise.js
const MyPromise = require('./myPromise')
function p1 () {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve('p1')
    }, 2000)
  })
}

function p2 () {
  return new MyPromise((resolve, reject) => {
    reject('p2 reject')
  })
}

p2().finally(() => {
  console.log('finallyp2')
  return p1()
}).then(value => {
  console.log(value)
}, reason => {
  console.log(reason)
})

// finallyp2
// 兩秒之后執(zhí)行p2 reject

十一、catch方法的實現(xiàn)

  • catch方法是為了捕獲promise對象的所有錯誤回調(diào)的
  • 直接調(diào)用then方法,然后成功的地方傳遞undefined,錯誤的地方傳遞reason
  • catch方法是作用在原型對象上的方法
// myPromise.js
catch (failCallback) {
    return this.then(undefined, failCallback)
}
// promise.js
const MyPromise = require('./myPromise')

function p2 () {
  return new MyPromise((resolve, reject) => {
    reject('p2 reject')
  })
}

p2()
  .then(value => {
    console.log(value)
  })
  .catch(reason => console.log(reason))

// p2 reject

Promise全部代碼整合

// myPromise.js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    try {
      exector(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }


  status = PENDING
  value = undefined
  reason = undefined
  successCallback = []
  failCallback = []

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

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

  then (successCallback = value => value, failCallback = reason => {throw reason}) {
    let promise2 = new Promise((resolve, reject) => {
      if(this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    });
    return promise2
  }

  finally (callback) {
    // 如何拿到當前的promise的狀態(tài),使用then方法,而且不管怎樣都返回callback
    // 而且then方法就是返回一個promise對象,那么我們直接返回then方法調(diào)用之后的結(jié)果即可
    // 我們需要在回調(diào)之后拿到成功的回調(diào),所以需要把value也return
    // 失敗的回調(diào)也拋出原因
    // 如果callback是一個異步的promise對象,我們還需要等待其執(zhí)行完畢,所以需要用到靜態(tài)方法resolve
    return this.then(value => {
      // 把callback調(diào)用之后返回的promise傳遞過去,并且執(zhí)行promise,且在成功之后返回value
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      // 失敗之后調(diào)用的then方法,然后把失敗的原因返回出去。
      return MyPromise.resolve(callback()).then(() => { throw reason })
    })
  }

  catch (failCallback) {
    return this.then(undefined, failCallback)
  }

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

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

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

module.exports = MyPromise
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容