Javascript 使用 Vue.js 异步/等待 axios 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50872310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Async/await axios calls with Vue.js
提问by GCien
I'm having a little trouble setting one of my this. values within my Vue.js application. I believe I'm either not understanding async axios calls correctly, or how async works within Vue.js.
我在设置其中一个时遇到了一些麻烦。我的 Vue.js 应用程序中的值。我相信我要么没有正确理解 async axios 调用,要么没有正确理解 async 在 Vue.js 中的工作原理。
I have the following three methods:
我有以下三种方法:
updateAvailability(availability) {
if (availability == true) {
this.showYourDetails();
} else {
this.showBookingDetails();
}
},
checkAvailability: async function(event) {
event.preventDefault();
const availability = await this.handleAvailabilityRequest(event);
this.loading = true;
console.log(availability); //This evaluates to undefined
const availabilityUpdate = await this.updateAvailability(availability);
this.loading = false;
},
handleAvailabilityRequest: async function(event) {
event.preventDefault();
let valid = this.validateFieldsForAvailabilityRequest(); //Ignore this for this particular question, assume valid is always true
if (valid) { // This is true
let config = {
headers: {
"X-CSRFToken": this.csrfToken,
"Content-Type": 'application/x-www-form-urlencoded',
}
}
let formData = new FormData();
let reservationTime = this.reservationHourSelected + ':' + this.reservationMinuteSelected;
formData.set('type', 'availability_request');
formData.set('session_name', this.sessionName);
formData.set('reservation_party_size', this.reservationPartySize);
formData.set('reservation_date', this.reservationDate);
formData.set('reservation_time', reservationTime);
await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response) {
this.availabilityMessage = response.data.message;
}).catch(function(error) {
this.availabilityMessage = false;
console.log(error);
});
}
return this.availabilityMessage;
}
My response.data.messageis being passed back from my framework as True/true but it seems I'm not returning anything from the await this.handleAvailabilityRequest()function? The post definitely hits the server as logging shows everything I want - then returns back message = true in json response context.
我response.data.message正在从我的框架中作为 True/true 传回,但似乎我没有从await this.handleAvailabilityRequest()函数中返回任何内容?当日志显示我想要的所有内容时,该帖子肯定会命中服务器 - 然后在 json 响应上下文中返回 message = true 。
So, I guess ... help! Completely dumbfounded as to why this isn't working other than it being an issue with waiting for the promise...
所以,我想……救命!除了等待承诺的问题之外,为什么这不起作用,完全傻眼了……
回答by CertainPerformance
The problem is here:
问题在这里:
await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response){
this.availabilityMessage = response.data.message;
}).catch(function (error) {
this.availabilityMessage = false;
console.log(error);
});
Because you're using a full-fledged function, your thisinside the .thendoes not refer to the instantiated object. Use an arrow function instead so that the thisis inherited from the outer scope:
因为您使用的是成熟的function,所以您的this内部.then不引用实例化的对象。改用箭头函数,以便this从外部作用域继承:
await axios.post('{{ request_absolute_uri }}', formData, config)
.then((response) => {
this.availabilityMessage = response.data.message;
}).catch((error) => {
this.availabilityMessage = false;
console.log(error);
});
回答by Vamsi Krishna
Why use promises pattern if you are using async await. This removes the use of callbacks and thisbinding being lost
如果您使用异步等待,为什么要使用承诺模式。这消除了回调和this绑定丢失的使用
You can do it like this
你可以这样做
handleAvailabilityRequest: async function (event) {
event.preventDefault();
...
try{
let response = await axios.post('{{ request_absolute_uri }}', formData, config)
this.availabilityMessage = response.data.message;
}catch(error) {
this.availabilityMessage = false;
console.log(error);
};
}
return this.availabilityMessage;
}
You can use try/catchblock for handling errors when using async/await
使用try/catch时可以使用块来处理错误async/await

