1

Here's a description of my problem:

i have an array containing ids for some flickr photosets. for each id, i need to make two nested apiCalls (one to flickr photosets api, one to photoinfo api) and add some html to my page

the structure is:

for(var i=0; i<ARRAY_ID.length; i++){

    $.getJSON(apiCall, function(data) {
         // some processing here

         $.getJSON(apiCall2,function(data){
              //other processing here

each "apiCall" is a string containing the correct call to the photosets api (apiCall) and then for the photoInfo api (apiCall2)

after all this processing, inside the "apiCall2" block, i append some html to a div (which results in as many block elements as the ARRAY_ID length).

There's where i have the strange behaviour: all appended block elems contain the same text and picture and links. It prints them out in the expected number, but the content is the same throu all of them. I guess it's the for loop not waiting for the $.getJSON to finish. How can i achieve this? I strictly need each json request to be finished before the next one is processed! Thanks all!

slowpoison
  • 586
  • 3
  • 20
Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63

3 Answers3

4

You seem to have 2 different, but related, issues going here.


all appended block elems contain the same text and picture and links. It prints them out in the expected number, but the content is the same throu all of them.

If you're referencing i within the callbacks, you'll need to enclose it within the for. Otherwise, with $.getJSON being asynchronous, the for will finish before the callbacks are called and i will always be the last value in the loop -- ARRAY_ID.length:

for(var i = 0; i < ARRAY_ID.length; i++) {
    (function (i) {
        // work with the local `i` rather than the shared `i` from the loop
    })(i);
}

I guess it's the for loop not waiting for the $.getJSON to finish. How can i achieve this? I strictly need each json request to be finished before the next one is processed!

You can't get the for to "wait" for each set of $.getJSON to finish. You can, however, use the for loop and closures to build a queue, which waits until you explicitly tell it next to continue:

var focus = $(...); // either match an existing element or create one: '<div />'

for(var i = 0; i < ARRAY_ID.length; i++) {
    (function (i) {
        focus.queue('apicalls', function (next) {
            $.getJSON(apiCall, function(data) {
                 // some processing here

                 $.getJSON(apiCall2,function(data){
                      //other processing here

                      next(); // start the next set of api calls
                 });
            });
        });
    })(i);
}

focus.dequeue('apicalls');
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • cheers, actually it was "i" and its scope's fault. also, thanks for the tip on the queue. ps: all the other answers were very valid too, this is just the most complete for my problem, but thanks all! – Samuele Mattiuzzo Apr 23 '12 at 20:51
  • @jonathan +1, btw the queue element can be an empty object `$({})` .. no need to create an DOM element.. – Gabriele Petrioli Apr 23 '12 at 21:02
  • 1
    @GabyakaG.Petrioli Hmm. [The docs don't seem to list](http://api.jquery.com/jQuery/#working-with-plain-objects) `.queue` or `.dequeue` as supported for that. Is it just undocumented? – Jonathan Lonowski Apr 23 '12 at 21:09
  • @JonathanLonowski, good point.. i always use it on empty objects without a hiccup. Looking at the [`source code`](https://github.com/jquery/jquery/blob/master/src/queue.js#L51-67) though, they seem to be building the queue object with `data()` which is supported, so i can't see why it would ever fail.. I will file a question with them though.. – Gabriele Petrioli Apr 23 '12 at 21:19
1

This is a common problem with closures. Your callbacks are inheriting the variables from the context of the function containing the for loop (I'll call it main function). Try this:

for(var i=0; i<ARRAY_ID.length; i++){

    $.getJSON(apiCall, (function(i, v1, v2, etc) { return function(data) {
        // some processing here


        $.getJSON(apiCall2,function(data){
        //other processing here
    })(i, v2, v3, etc));
}

Basically, now you are changing the context from which the closure is accessing variables from. You create an anonymous function and pass all the variables you are accessing from the main function. In the example, I'm passing variable i, and v1, v2, etc, denote other variables you might be accessing.

By creating the right context for each closure call, you should be able to fix this problem.

slowpoison
  • 586
  • 3
  • 20
1

Most likely it is a scope issue.

If your callbacks passed to the getJSON method use the i variable of the loop, then they most likely all end using the last value of i.

The solution would be

function handleJsonRequests(index,id){
 // use index instead of i
 // use id instead of ARRAY_ID[i]

 $.getJSON(apiCall, function(data) {
         // some processing here

         $.getJSON(apiCall2,function(data){
              //other processing here

}// end of function

for(var i=0; i<ARRAY_ID.length; i++){
    handleJsonRequests(i, ARRAY_ID[i]);
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317