【发布时间】:2019-03-08 19:54:28
【问题描述】:
我有以下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/
它只是不起作用。日志在请求完成之前执行,即发生一些错误之后。请帮忙。
【问题讨论】:
-
“日志在请求完成之前被执行。”——不,不会发生。
-
jsbin.com/ropuwejomo/1/edit?html,js,console — 我无法重现该问题。
-
我添加了一个 Vue Demo!请检查。有错误但仍然记录结果。
-
@Sanjay — 当您说“您怎么知道请求已完成?”您的意思是要问“如何区分请求完成和抛出异常?”
标签: javascript asynchronous vue.js promise async-await