我有以下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/
这根本行不通。日志在请求完成之前执行,即发生一些错误之后。请帮忙。
最佳答案
The log gets executed […] after some error has occured.
是的,在新的 todo
方法中,您捕获
错误,然后返回 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)
}
}
关于javascript - 如何在 async/await 中实现 Promise 的 then ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55060918/