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