0

I, I know, there is a lot information about this on SO, but I didn't find the right answer for my situation.

I have this piece of code:

for(var i=0; i < shop.collections.length; i++){
  if(!shop.collection[i].active){
    var data = {
      name: shop.collection[i].name,
      visible: true
    };

    myOwnService.createCollection(data, accessToken, function(err, response, body){
      shop.collections[i].serviceId = body.id;
  })
}

My problem is that shop is undefined in the myOwnService.createCollection() service. What is the right way to access the shop variable in the callback, so how I can update the object so I can save the result?

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
NVO
  • 2,566
  • 5
  • 27
  • 57

2 Answers2

2

shop is in the parent scope of the myOwnService.createCollection function hence it is accessible inside it.

Only issue in above code is i used in callback which will always be the last value as it will be executed after event loop.

Use IIFE wrapper around myOwnService.createCollection so that scope of i could be passed.

for (var i = 0; i < shop.collections.length; i++) {
  if (!shop.collection[i].active) {
    var data = {
      name: shop.collection[i].name,
      visible: true
    };
    (function(i) {
      myOwnService.createCollection(data, accessToken, function(err, response, body) {
        shop.collections[i].serviceId = body.id;
      });
    })(i);
  }
}
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

It should be accessible inside where you try to access. If you are tying Chrome debugger to see if it has the value, Chrome debugger sometime mess up and shows it like is not available.

https://bugs.chromium.org/p/v8/issues/detail?id=3491

serkan
  • 6,885
  • 4
  • 41
  • 49