以下两个函数其实执行效果都一样。就这个问题我在群里跟别人争执很久,但是我也看了MDN案例使用try...catch,但是我看着写一堆try...catch在外面,看着难受。老师为啥我后面链式调用完了,这样写有什么缺点?
以下写了查询列表获取数据的两种方式:
inquireList函数的await后面使用了axios返回的promise链式调用then和catch都加上了。inquireList2函数的await后面使用了axios返回promise,在try...catch。以下伪代码:
async inquireList() {
this.listLoading = true
const params = {}
await axios.get('/list', {params})
.then((res)=> {
if (res.data && res.data.code === 200) {
this.listData = res.data.data
}
})
.catch((e)=> {
console.log(e)
})
this.listLoading = false
}
async inquireList2() {
this.listLoading = true
const params = {}
const res = await axios.get('/list', {params})
try {
if (res.data && res.data.code === 200) {
this.listData = res.data.data
}
} catch (e) {
console.log(e)
}
this.listLoading = false
}