Promise.then()
和Promise.catch()
的理解今天碰到問題是這樣子的:
調試bug的時候發現axios走了then也走了有catch,在我印象裏是走了then就不應走catch(後來發現是我理解錯了)
代碼是這樣的ios
this.axios.post('/user/login', params) .then(res => { console.log('response', res) }) .catch(err => { // 這個catch catch的是then裏的異常,then裏若是有任何異常都會被catch捕獲 console.log('catch') console.error(err.message) })
仔細看了Promise.catch()
MCDN是這樣解釋的axios
The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected) (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)).
簡單來說調用Promise.catch()
等於調用Promise.prototype.then(undefined, onRejected)
因爲Promise.then()
返回的是一個Promise
對象,返回值解釋以下:segmentfault
throws an error, the promise returned by then gets rejected with the thrown error as its value;
若是拋出異常返回一個執行rejected
的Promise
對象即至關於調用返回Promise
的Promise.then(undefined, onRejected)
promise
對於Promise.catch()
的返回值是這樣解釋的:dom
The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.
若是Promise.catch()
又拋出異常則至關於又調用Promise.then(undefined, onRejected)
若是未拋出異常則至關於調用Promise.then(onResolved,undefined)
異步
// 示例代碼 const getRandom = () => +(Math.random()*1000).toFixed(0); const asyncTask = taskID => new Promise(resolve => { let timeout = getRandom(); console.log(`taskID=${taskID} start.`); setTimeout(function() { console.log(`taskID=${taskID} finished in time=${timeout}.`); resolve(taskID) }, timeout); }); Promise.all([asyncTask(1),asyncTask(2),asyncTask(3)]) .then(resultList => { console.log('results:',resultList); });
詳見這裏async