Nate
Nate

Reputation: 7856

Pass variable to a promised function

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

Answers (2)

GregL
GregL

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

Arun P Johny
Arun P Johny

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

Related Questions