1

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?

Nate
  • 7,606
  • 23
  • 72
  • 124

2 Answers2

4

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);
    });
})
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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);
}
GregL
  • 37,147
  • 8
  • 62
  • 67