Wait for .each() .getJSON request to finish before executing a callback

…衆ロ難τιáo~ 提交于 2019-12-11 00:47:26

问题


I have a jquery .each loop that retrieves remote data from a json request for all the elements on a page with a certain class. One set of the elements is a group of li tags that I would like to sort using another function after the li element has been updated with the remote information.

Passing in the sort function after the .each loop does not sort the list because the items have not finished loading from the json request. The sorting works If I pass in the sort function as a .complete callback for the getJSON request but I only want the sort to run once for the whole list, not for each item.

fetch_remote_data(function(){sort_list_by_name();});

function fetch_remote_data(f){
jQuery('.fetching').each(function(){
   var oj = this;
   var kind = this.getAttribute('data-kind');
   var url = "http://something.com"
   jQuery.getJSON(url, function(json){
       $(oj).text(json[kind]);
       $(oj).toggleClass('fetching');
   });
});
 if (typeof f == 'function') f();
};

Any suggestions?


回答1:


If you're using jQuery 1.5, you could take advantage of its $.Deferred implementation:

function fetch_remote_data(f) {
  var requests = [],
      oj = this,
      url = "http://something.com";

  $('fetching').each(function() {
    var request = $.getJSON(url, function(json) {
      $(oj).text(json['name']);
      $(oj).toggleClass('fetching');
    });

    requests.push(request);
  });

  if (typeof f === 'function') 
    $.when(requests).done(f);
}

// No need to wrap this in another function.
fetch_remote_data(sort_list_by_name);

I'm assuming the $('fetching') bit in your example isn't real code? That selector would be searching for <fetching> elements in the DOM, which probably isn't what you want.




回答2:


Try to get the total number of fetches to be be performed before fireing each(). Than attach the .complete callback in which you first increase some count of completed requests and sort only if the number of completed equals to the total number to be performed. In principle, you should run sort only after all ajax called has finished...K



来源:https://stackoverflow.com/questions/6462144/wait-for-each-getjson-request-to-finish-before-executing-a-callback

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