重讀es6, 正確了解promise中catch的用法


前言

在最近的項目中,用到了es6的promise語法,發現promise.prototype.catch 並不只是單單reject拋出的回調函數,所以今天做一些筆錄,防止以后在項目中又碰到這樣的問題。

先介紹一下promise.prototype.catch

Promise.prototype.catch 方法是 .then(null, rejection) 或是 .then(undefined, rejection)的別名,用於指定發生錯誤時的回調函數。

如果Promise 對象狀態變為resolved,則會調用then方法指定的回調函數;如果異步操作拋出錯誤,狀態就會變為rejected,就會調用catch方法指定的回調函數,處理這個錯誤。另外,then方法指定的回調函數,如果運行中拋出錯誤,也會被catch方法捕獲。

下面是摘抄阮一峰的es6入門的

p.then((val) => console.log('fulfilled:', val))
  .catch((err) => console.log('rejected', err));

// 等同於
p.then((val) => console.log('fulfilled:', val))
  .then(null, (err) => console.log("rejected:", err));

下面是我自己寫的例子

const testPromise = new Promise(function (resolve, reject) {
    let a = 5
    if (a === 5) {
      resolve('success')
    } else {
      reject('catch error')
    }
  })
  testPromise.then(res => {
    throw new Error('then error')
  }).catch(err => {
    console.log('catch error')
    console.log(err)
  })

這個例子最終會先輸出catch error,然后再拋出錯誤信息。

總結

then中拋出錯誤,就會調用promise.prototype.catch的回調函數。


免責聲明!

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



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