1
userId = ['123', '456'];
userName = ['aaa', 'bbb'];
for (var j = 0; j < userId.length; j++) {
            Instagram.otherUserMedia(userId[j], function (response) {
                $('#otherInfo').append('<h2>' + userName[j] + '</h2>');
                for(var i = 0; i < response.data.length; i++) {
                    $('#otherInfo').append('<img src="' + response.data[i].images.thumbnail.url + '" />');
                }
            });
        }

In this code snippet, I need to show corresponding userName with the output images from response. But when I execute this code, value of j increments till userId.length and then enters the callback. So, when I want to show the userName[j] it says j is undefined because it has loop through every value in userId. I want to get corresponding userName for every userId's response.

Abhishek Singh
  • 125
  • 1
  • 4
  • Use the array's `forEach` method instead. – Felix Kling Jun 02 '16 at 05:39
  • 1
    There are a zillion dups of this. Here's another one [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop/11488129#11488129) – jfriend00 Jun 02 '16 at 05:39

1 Answers1

2

It'a problem related to JavaScript Closure.

A following demo could be one of the solutions;

userId = ['123', '456'];
userName = ['aaa', 'bbb'];
for (var j = 0; j < userId.length; j++) {
  Instagram.otherUserMedia(userId[j], (function(index) {
    return function(response) {
      $('#otherInfo').append('<h2>' + userName[index] + '</h2>');
      for (var i = 0; i < response.data.length; i++) {
        $('#otherInfo').append('<img src="' + response.data[i].images.thumbnail.url + '" />');
      };
    }
  }(j)));
}

You may want to check resources like following:
How do JavaScript closures work?
Closures
Immediately-Invoked Function Expression (IIFE)

Community
  • 1
  • 1
user1577263
  • 449
  • 5
  • 8