await的使用问题。
来源:8-11 async-await和Promise有什么关系

zhangweb
2022-03-19
提问:
以下两个函数其实执行效果都一样。就这个问题我在群里跟别人争执很久,但是我也看了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
}
写回答
2回答
-
双越
2022-03-19
第一,你都用 await 了,就别再用 then 了。await 和 promise 混用,很不易读
第二,try catch 一般是把 await 也包含进去的,而不是在 await 后面。
00 -
双越
2022-03-19
看着有点乱。你的核心问题是什么?
022022-03-19
相似问题