使用Vue.js异步/等待axios调用 [英] Async/await axios calls with Vue.js

查看:765
本文介绍了使用Vue.js异步/等待axios调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置其中一项时遇到了一些麻烦.我的Vue.js应用程序中的值.我相信我不是正确地理解了异步axios调用,还是异步在Vue.js中是如何工作的.

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.

我有以下三种方法:

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()函数返回任何信息吗?该日志肯定会到达服务器,因为日志记录显示了我想要的一切-然后在json响应上下文中返回message = true.

My response.data.message is 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.

所以,我想...帮助!除了为什么要等待诺言这是个问题之外,其他人对此完全傻眼了.

So, I guess ... help! Completely dumbfounded as to why this isn't working other than it being an issue with waiting for the promise...

推荐答案

问题在这里:

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,因此.then中的this不会引用实例化的对象.请改用箭头函数,以便this从外部范围继承:

Because you're using a full-fledged function, your this inside the .then does not refer to the instantiated object. Use an arrow function instead so that the this is inherited from the outer scope:

await axios.post('{{ request_absolute_uri }}', formData, config)
.then((response) => {
  this.availabilityMessage = response.data.message;
}).catch((error) => {
  this.availabilityMessage = false;
  console.log(error);
});

这篇关于使用Vue.js异步/等待axios调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆