[Vuejs]-How to send the index of a for loop into the promise of a function in a Vue Resource call?

2👍

Always use let to initialize variables in for loop when dealing with async operations. Similar things goes to having for loops in intervals. By using let you make sure you always have a unique variable assigned to i.

for (let i = 0, recommendationlength = vm.recommendationResponse['recommendedItems'].length; i < recommendationlength; i++)

Little bonus, if you cache array length in the beginning you get a small performance boost 🙂

0👍

You could use Array.prototype.forEach instead:

var vm = this;  
vm.recommendataionResponse['recommendedItems'].forEach((item, i) => {
  var sku = vm.recommendationResponse['recommendedItems'][i]['items'][0]['id'];
  vm.$http.get('http://127.0.0.1:8000/models/api/productimage/' + sku).then(response => {
    // get body data
    vm.recommendationResponse['recommendedItems'][i]['items'][0]['image_url'] = response.body['product_image_url'];
    vm.recommendationResponse['recommendedItems'][i]['items'][0]['price'] = response.body['price'];
  }, response => {
    vm.recommendationResponse['recommendedItems'][i]['items'][0]['image_url'] = '';
    vm.recommendationResponse['recommendedItems'][i]['items'][0]['price'] = '';
  });
})

This way, since there is a unique scope for each i value, each .then callback will be able to reference the correct value.

Leave a comment