我有以下async/await
方法:
async todo() {
const res = await axios.get('/todo')
}
getTodo() {
this.todo()
}
现在,在async/await
中,您如何知道请求已完成(200)?在Promises中,我们仅使用then
:
// store/todo.js
todo() {
const res = axios({
method: 'GET',
url: '/todo'
})
return res
}
// components/Todo.vue
getTodo() {
this.todo().then(res => {
console.log('Request Executed Successfully!')
})
}
这很好用,但是当我尝试在getTodo中添加async/await
并执行以下操作时:
async todo() {
try {
const res = await axios.get('/todo')
return res
} catch(e) {
console.log(e)
}
}
async getTodo() {
try {
await this.todo()
console.log('Request Completed')
} catch(e) {
console.log(e)
}
}
演示:https://jsfiddle.net/jfn483ae/
它根本不起作用。在请求完成之前(即发生某些错误之后)执行日志。请帮忙。
答案 0 :(得分:2)
发生某些错误后,日志将被执行[…]。
是的,在新的todo
方法中,您catch
出现了错误,然后以正常结果返回undefined
。只是当您无法处理错误时不要使用try
/ catch
,使用与原来相同的代码,并且await
时,promise也会起作用:
todo() {
return axios({
method: 'GET',
url: '/todo'
})
}
async getTodo() {
try {
await this.todo()
console.log('Request Completed')
} catch(e) {
console.log(e)
}
}