对于Promise.then()
和Promise.catch()
的理解
今天碰到问题是这样子的:
调试bug的时候发现axios走了then也走了有catch,在我印象里是走了then就不该走catch(后来发现是我理解错了)
代码是这样的
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是这样解释的
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
对象,返回值解释如下:
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.catch()
的返回值是这样解释的:
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)
promise.all()是顺序开始,异步执行,顺序返回
// 示例代码
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);
});
详见这里
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。