$.getJSON calls misbehaving inside a for loop

夙愿已清 提交于 2019-12-23 03:57:09

问题


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!


回答1:


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



回答2:


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.




回答3:


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]);
}


来源:https://stackoverflow.com/questions/10287594/getjson-calls-misbehaving-inside-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!