我在设置我的一个时遇到了一些麻烦。我的Vue.js应用程序中的值。我相信我要么不正确理解异步axios调用,要么在Vue.js中如何异步工作。
我有以下三种方法:
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;
}
我的response.data.message
正从我的框架传回True / true,但似乎我没有从await this.handleAvailabilityRequest()
函数返回任何内容?当post记录显示我想要的所有内容时,帖子肯定会命中服务器 - 然后在json响应上下文中返回message = true。
所以,我猜......帮忙!完全傻眼了,为什么这不起作用,除了它等待承诺的问题......
答案 0 :(得分:7)
问题在于:
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);
});
由于您使用的是完整的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);
});
答案 1 :(得分:6)
如果使用异步等待,为什么要使用promises模式。这样就无法使用回调和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;
}
使用try/catch
async/await
块来处理错误