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

目錄

  • 1、Promise核心邏輯實現
  • 2、在 Promise 類中加入異步邏輯
  • 3、實現 then 方法屢次調用添加多個處理函數
  • 4、實現then方法的鏈式調用
  • 5、then方法鏈式調用識別 Promise 對象自返回
  • 6、捕獲錯誤及 then 鏈式調用其餘狀態代碼補充編程

      1. 捕獲執行器的錯誤
      1. then執行的時候報錯捕獲
      1. 錯誤以後的鏈式調用
      1. 異步狀態下鏈式調用
  • 7、將then方法的參數變成可選參數
  • 8、promise.all方法的實現
  • 9、Promise.resolve方法的實現
  • 10、finally 方法的實現
  • 11、catch方法的實現
  • Promise所有代碼整合
這裏只是對Promise源碼的實現作一個剖析,若是想對Promise總體有個瞭解,<br/>
請看 ES6(十一)—— Promise(更優的異步編程解決方案)

1、Promise核心邏輯實現

首先分析其原理segmentfault

  1. promise就是一個類<br/>

在執行類的時候須要傳遞一個執行器進去,執行器會當即執行數組

  1. Promise中有三種狀態,分別爲成功-fulfilled 失敗-rejected 等待-pending<br/>
    pending -> fulfilled<br/>
    pending -> rejected<br/>
    一旦狀態肯定就不可更改
  2. resolvereject函數是用來更改狀態的<br/>

resolve:fulfilled<br/>
reject:rejectedpromise

  1. then方法內部作的事情就是判斷狀態

若是狀態是成功,調用成功回調函數<br/>
若是狀態是失敗,就調用失敗回調函數<br/>
then方法是被定義在原型對象中的併發

  1. then成功回調有一個參數,表示成功以後的值;then失敗回調有一個參數,表示失敗後的緣由

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

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

  // 實例對象的一個屬性,初始爲等待
  status = PENDING
  // 成功以後的值
  value = undefined
  // 失敗以後的緣由
  reason = undefined

  // resolve和reject爲何要用箭頭函數?
  // 若是直接調用的話,普通函數this指向的是window或者undefined
  // 用箭頭函數就可讓this指向當前實例對象
  resolve = value => {
    // 判斷狀態是否是等待,阻止程序向下執行
    if(this.status !== PENDING) return
    // 將狀態改爲成功
    this.status = FULFILLED
    // 保存成功以後的值
    this.value = value
  }

  reject = 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)
    }
  }
}

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)
 })

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

上面是沒有通過異步處理的,若是有異步邏輯加進來,會有一些問題異步編程

//promise.js
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
  // 主線程代碼當即執行,setTimeout是異步代碼,then會立刻執行,
  // 這個時候判斷promise狀態,狀態是pending,然而以前並無判斷等待這個狀態
  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
  // 定義一個成功回調參數
  successCallback = undefined
  // 定義一個失敗回調參數
  failCallback = undefined

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

  reject = reason => {
    if(this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // 判斷失敗回調是否存在,若是存在就調用
    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

3、實現 then 方法屢次調用添加多個處理函數

promisethen方法是能夠被屢次調用的。ui

這裏若是有三個then的調用,this

  • 若是是同步回調,那麼直接返回當前的值就行;
  • 若是是異步回調,那麼保存的成功失敗的回調,須要用不一樣的值保存,由於都互不相同。

以前的代碼須要改進。

//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)
})

保存到數組中,最後統一執行

// 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
    // 判斷成功回調是否存在,若是存在就調用
    // 循環回調數組. 把數組前面的方法彈出來而且直接調用
    // shift方法是在數組中刪除值,每執行一個就刪除一個,最終變爲0
    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) {
    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

4、實現then方法的鏈式調用

  • then方法要鏈式調用那麼就須要返回一個promise對象,
  • then方法的return返回值做爲下一個then方法的參數
  • then方法還一個return一個promise對象,那麼若是是一個promise對象,那麼就須要判斷它的狀態
// 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回調函數的return返回值
        // 判斷 x 的值時普通值仍是promise對象
        // 若是是普通紙 直接調用resolve
        // 若是是promise對象 查看promise對象返回的結果
        // 再根據promise對象返回的結果 決定調用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

5、then方法鏈式調用識別 Promise 對象自返回

若是then方法返回的是本身的promise對象,則會發生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須要執行完成以後纔有promise2,同步代碼中沒有pormise2,
        // 因此這部分代碼須要異步執行
        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')
})
 
// 這個時候將promise定義一個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>

6、捕獲錯誤及 then 鏈式調用其餘狀態代碼補充

目前咱們在Promise類中沒有進行任何處理,因此咱們須要捕獲和處理錯誤。

1. 捕獲執行器的錯誤

捕獲執行器中的代碼,若是執行器中有代碼錯誤,那麼promise的狀態要弄成錯誤狀態

// myPromise.js
constructor (exector) {
    // 捕獲錯誤,若是有錯誤就執行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('執行器錯誤')
})
 
promise.then(value => {
  console.log(1)
  console.log('resolve', value)
}, reason => {
  console.log(2)
  console.log(reason.message)
})

//2
//執行器錯誤

2. then執行的時候報錯捕獲

// myPromise.js
then (successCallback, failCallback) {
    let promise2 = new Promise((resolve, reject) => {
        if(this.status === FULFILLED) {
            setTimeout(() => {
                // 若是回調中報錯的話就執行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('執行器錯誤')
 })
 
// 第一個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. 錯誤以後的鏈式調用

// 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)
        // 在狀態是reject的時候對返回的promise進行處理
        } else if (this.status === REJECTED) {
            setTimeout(() => {
                // 若是回調中報錯的話就執行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('執行器錯誤')
 })
 
 // 第一個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
// 執行器錯誤
// 3
// 100

4. 異步狀態下鏈式調用

仍是要處理一下若是promise裏面有異步的時候,then的鏈式調用的問題。

// myPromise.js
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
  constructor (exector) {
    // 捕獲錯誤,若是有錯誤就執行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
    // 異步回調傳值
    // 調用的時候不須要傳值,由於下面push到裏面的時候已經處理好了
    while(this.successCallback.length) this.successCallback.shift()()
  }

  reject = reason => {
    if(this.status !== PENDING) return
    this.status = REJECTED
    this.reason = reason
    // 異步回調傳值
    // 調用的時候不須要傳值,由於下面push到裏面的時候已經處理好了
    while(this.failCallback.length) this.failCallback.shift()()
  }

  then (successCallback, failCallback) {
    let promise2 = new Promise((resolve, reject) => {
      if(this.status === FULFILLED) {
        setTimeout(() => {
          // 若是回調中報錯的話就執行reject
          try {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          // 若是回調中報錯的話就執行reject
          try {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        // 處理異步的成功錯誤狀況
        this.successCallback.push(() => {
          setTimeout(() => {
            // 若是回調中報錯的話就執行reject
            try {
              let x = successCallback(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
        this.failCallback.push(() => {
          setTimeout(() => {
            // 若是回調中報錯的話就執行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

7、將then方法的參數變成可選參數

then方法的兩個參數都是可選參數,咱們能夠不傳參數。
下面的參數能夠傳遞到最後進行返回

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) {
    // 這裏進行判斷,若是有回調就選擇回調,若是沒有回調就傳一個函數,把參數傳遞
    successCallback = successCallback ? successCallback : value => value
    // 錯誤函數也是進行賦值,把錯誤信息拋出
    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

8、promise.all方法的實現

promise.all方法是解決異步併發問題的

// 若是p1是兩秒以後執行的,p2是當即執行的,那麼根據正常的是p2在p1的前面。
// 若是咱們在all中指定了執行順序,那麼會根據咱們傳遞的順序進行執行。
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方法接收一個數組,數組中能夠是普通值也能夠是promise對象
  • 數組中值得順序必定是咱們獲得的結果的順序
  • promise返回值也是一個promise對象,能夠調用then方法
  • 若是數組中全部值是成功的,那麼then裏面就是成功回調,若是有一個值是失敗的,那麼then裏面就是失敗的
  • 使用all方法是用類直接調用,那麼all必定是一個靜態方法
//myPromise.js
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) {
          // promise對象就執行then,若是是resolve就把值添加到數組中去,若是是錯誤就執行reject返回
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          // 普通值就加到對應的數組中去
          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"]
})

9、Promise.resolve方法的實現

  • 若是參數就是一個promise對象,直接返回,若是是一個值,那麼須要生成一個promise對象,把值進行返回
  • Promise類的一個靜態方法
// 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

10、finally 方法的實現

  • 不管當前最終狀態是成功仍是失敗,finally都會執行
  • 咱們能夠在finally方法以後調用then方法拿到結果
  • 這個函數是在原型對象上用的
// myPromise.js
finally (callback) {
    // 如何拿到當前的promise的狀態,使用then方法,並且無論怎樣都返回callback
    // 並且then方法就是返回一個promise對象,那麼咱們直接返回then方法調用以後的結果便可
    // 咱們須要在回調以後拿到成功的回調,因此須要把value也return
    // 失敗的回調也拋出緣由
    // 若是callback是一個異步的promise對象,咱們還須要等待其執行完畢,因此須要用到靜態方法resolve
    return this.then(value => {
      // 把callback調用以後返回的promise傳遞過去,而且執行promise,且在成功以後返回value
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      // 失敗以後調用的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
// 兩秒以後執行p2 reject

11、catch方法的實現

  • catch方法是爲了捕獲promise對象的全部錯誤回調的
  • 直接調用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的狀態,使用then方法,並且無論怎樣都返回callback
    // 並且then方法就是返回一個promise對象,那麼咱們直接返回then方法調用以後的結果便可
    // 咱們須要在回調以後拿到成功的回調,因此須要把value也return
    // 失敗的回調也拋出緣由
    // 若是callback是一個異步的promise對象,咱們還須要等待其執行完畢,因此須要用到靜態方法resolve
    return this.then(value => {
      // 把callback調用以後返回的promise傳遞過去,而且執行promise,且在成功以後返回value
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      // 失敗以後調用的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
相關文章
相關標籤/搜索