Promise 如何默認處理 catch


起因

為了方便管理,封裝全局請求方法的時候,需要對異步請求返回值進行統一的異常處理,符合的值就走 then 進行返回,不符合的數據走 catch 進行返回或者處理。

需求

1、當執行 Promise 方法出現異常時自動調用 catch 並執行對應的處理方法
2、需要單獨手動處理 catch 時可以自行手動調用 catch 進行錯誤處理
3、手動調用 catch 時要覆蓋掉默認執行的 catch

比如

const p = MyPromise() // promise 方法

p.then() // 出錯時自動執行默認的 catch

p.then().catch(res=>{}) // 手動調用 catch

解決

核心方法如下,catch 默認將報錯信息進行輸出。

function RequestPromise(originalPromise) {
  this._promise = originalPromise

  this._catchyPromise = Promise.resolve()
    .then(() => this._promise)
    .catch(err => console.error('Error', err))

  // every method but 'constructor' from Promise.prototype
  const methods = ['then', 'catch', 'finally']

  for (const method of methods) {
    this[method] = function (...args) {
      this._promise = this._promise[method](...args)

      return this
    }
  }
}

由於項目中使用了 flyio ,下面例子基於該請求庫

// post 請求封裝
export const post = (uri, data, config)=> {
  return new RequestPromise(new Promise((resolve, reject) => {
    fly
      .post(uri, data, config)
      .then(response => {
        const { success, data } = response.data
        if (success) return resolve(data)
        return reject(response.data)
      })
      .catch(reject)
  }))
}
// 報錯時默認執行 catch
post(URL).then()

// 手動處理報錯信息
post(URL).then().catch(error=>{
      // TODO
})

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM