Reputation: 7856
I call an async function that doesn't 'belong' to me inside a loop. I need to get retrieve a variable inside the 'then' function. Here is how I do it:
for(var int = 0; int < attachments.length; int++) {
dp.getAttachment(attachments[int]).then(function (response) {
console.log(int);
});
}
How can I send the int so I can get it inside the function?
Upvotes: 1
Views: 85
Reputation: 38103
Using the power of closures, you can ensure a copy of each value of the int
variable is available when the then
callback gets invoked.
for(var int = 0; int < attachments.length; int++) {
(function(int) {
dp.getAttachment(attachments[int]).then(function (response) {
console.log(int);
});
})(int);
}
Upvotes: 1
Reputation: 388316
The problem is the wrong use of a closure variable in a loop.
Here since you have an array, you can create a local closure by using forEach() to iterate over it
attachments.forEach(function (item, it) {
dp.getAttachment(item).then(function (response) {
console.log(int);
});
})
Upvotes: 4