Async/await axios calls with Vue.js

2020-06-03 02:53发布

问题:

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.

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? 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...

回答1:

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. 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);
});


回答2:

Why use promises pattern if you are using async await. This removes the use of callbacks and this binding being lost

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