0

I can't access variables from inside the function, how to do it in the data scope? Only an empty global this object appears in the console.

var app = new Vue({
el: '#app',
delimiters: ['{%', '%}'],
data: function () {
  return {
    boxes: [],

  }
},
methods: {
// Обработчик кнопки
  search_boxes: function (event) {
    if(this.boxes.length == 0) {
      this.get_boxes(); 

      console.log(this);
      console.log(this.boxes.length);
      console.log(this.boxes);
    }
    console.log(this.boxes);
  },
  get_boxes: function () {
    axios.get('/api/get_boxes')
      .then(response => { this.boxes = response.data; })
      .catch(e => { console.log(e); });
    }
},

});

  • `axios.get()` is an async function that returns a promise. So when you call `get_boxes()` it proceeds instantly without waiting for the response. Therefore your logs are showing the empty `boxes` variable – Jozott Jun 24 '21 at 14:54
  • how, then, to continue working with the data object? – Jarosław Bielawski Jun 24 '21 at 15:05
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – ponury-kostek Jun 24 '21 at 15:06

1 Answers1

0

axios.get() is an async function that returns a promise. So when you call get_boxes() it proceeds instantly without waiting for the response. Therefore your logs are showing the empty boxes variable

var app = new Vue({
el: '#app',
delimiters: ['{%', '%}'],
data: function () {
  return {
    boxes: [],

  }
},
methods: {
// Обработчик кнопки
  search_boxes: async function (event) {
    if(this.boxes.length == 0) {
      await this.get_boxes(); 

      console.log(this);
      console.log(this.boxes.length);
      console.log(this.boxes);
    }
    console.log(this.boxes);
  },
  get_boxes: function () {
   return axios.get('/api/get_boxes')
      .then(response => { this.boxes = response.data; })
      .catch(e => { console.log(e); });
    }
},

By turning the search_boxes() function into an async one, we can await the promise of the response. So when we call this.get_boxes() we gonna wait until the data is stored in this.boxes.

Jozott
  • 2,367
  • 2
  • 14
  • 28