简体   繁体   English

使用Vue.js异步/等待axios调用

[英]Async/await axios calls with Vue.js

I'm having a little trouble setting one of my this. 设置我的一个,我有点麻烦。 values within my Vue.js application. 我的Vue.js应用程序中的值。 I believe I'm either not understanding async axios calls correctly, or how async works within Vue.js. 我相信我要么不正确理解异步axios调用,要么在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.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? 我的response.data.message正从我的框架传回True / true但似乎我没有从await this.handleAvailabilityRequest()函数返回任何东西? The post definitely hits the server as logging shows everything I want - then returns back message = true in json response context. 当post记录显示我想要的所有内容时,帖子肯定会命中服务器 - 然后在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... 完全傻眼了,为什么这不起作用,除了它等待承诺的问题......

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 this inside the .then does not refer to the instantiated object. 因为你正在使用一个完整的function ,你在.then中的this function并不是指实例化的对象。 Use an arrow function instead so that the this is inherited from the outer scope: 使用代替了箭头功能this是从外部作用域继承:

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

Why use promises pattern if you are using async await. 如果您使用异步等待,为什么要使用promises模式。 This removes the use of callbacks and this binding 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/catch block for handling errors when using async/await 使用async/await时,可以使用try/catch块处理错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM