0

I've a JSON object like this

var Obj = {
    'id1': 'abc',
    'id2': 'pqr',
    'id3': 'xyz'
}

and I'm calling async method while iterating, like this

var otherObj = {};
for (i in Obj) {

    var someData = Obj[i];

    File.upload(someData).then(function(response) {
        otherObj[i] = response.data.url;
    });
}

But in this I'm getting otherObj as

otherObj = {
    'id3':'url1',
    'id3':'url2',
    'id3':'url3',
}

So my question is what is the best way to correctly associate each key present in Obj object with the response of File.upload().

Tushar
  • 1,115
  • 1
  • 10
  • 26
  • Take a look http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – rafaelc May 28 '15 at 03:25

1 Answers1

1

You need to use an IIFE

for (i in Obj) {

    var someData = Obj[i];
    (function(i) {
        File.upload(someData).then(function(response) {
            otherObj[i] = response.data.url;
        });
    })(i);
}

This will preserve i in the execution context of the callback for File.upload().then. What was happening before is each File.upload().then was 'seeing' the last iterated i which was visible to all callbacks.

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53