Search code examples
javascriptjsonflickr

$.getJSON calls misbehaving inside a for loop


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!


Solution

  • 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');