0

I am using this piece of code to retrieve some JSONs from twitch:

for (var i = 0; i < streamList.length; i++) {
     $.get(baseURL + streamList[i], getStreamInfo, "json");
}  

where getStreamInfo is the callback function. I would like to know if it is possible to pass the value of "i" to the callback function somehow, along with the JSON.

user3082880
  • 49
  • 1
  • 6

3 Answers3

2

Yes, you can pass the default parameter that receive the data of the ajax query and then add the i var.

 for (var i = 0; i < streamList.length; i++) {
     $.get(baseURL + streamList[i],
           function(data) { getStreamInfo(data, i) }, 
           "json");
 } 

Note that you need to receive it in getStreamInfo function

Hope it helps.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
  • Nope... https://jsfiddle.net/gbf0fwqo/ - [Javascript infamous Loop issue?](https://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue) – Andreas Sep 15 '15 at 12:14
2

You can add any variables you want to the anonymous object. Be sure those variables are not used by the get function. For exemple, I added the variable foo to the anonymous object and used it with this.foo in the callback function :

for (var i = 0; i < streamList.length; i++) {
    $.get({
      url: baseURL + streamList[i],
      success: getStreamInfo,
      dataType: "json",
      foo:i
    });
} 

function getStreamInfo()
{
    var i = this.foo;
}
Théo Bouveret
  • 209
  • 2
  • 9
1

You can use Closures.

for (var i = 0; i < streamList.length; i++) {
    (function(index){
        $.get(baseURL + streamList[i], function(data){
            getStreamInfo(data, index);
        }, "json");
    })(i);     
} 

Note: Modify your function getStreamInfo to accept index.

Read How do JavaScript closures work?

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168