Nodejs Local Variable In Callback
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.lengt
Solution 1:
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);
}
}
Solution 2:
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.
Post a Comment for "Nodejs Local Variable In Callback"