How to use .promise().done() on $.each json array when done/completed?

会有一股神秘感。 提交于 2019-12-03 08:48:09

问题


I want to perform some action when $.each is done.

$.each(someArray, function(index, val) {

    //---------some async ajax action here per loop ---------
    $.ajax({...}).done(function(data){...});

}.promise().done(function(){...}); //<-------error here can't use with $.each
  • Not every jQuery function has a promise()?
  • How do I know when $.each array is done?
  • Can I change someArray to $someArray to use it?

回答1:


As you've figured out, $.each() doesn't have a .promise() so you can't do it the way you were trying to. Instead, you can use $.when() to track when a bunch of promises returned by a group of Ajax functions have all been resolved:

var promises = [];
$.each(someArray, function(index, val) {
    //---------some async ajax action here per loop ---------
    promises.push($.ajax({...}).then(function(data){...}));
});
$.when.apply($, promises).then(function() {
    // code here when all ajax calls are done
    // you could also process all the results here if you want
    // rather than processing them individually
});

Or, rather than your $.each(), it's a bit cleaner to use .map():

$.when.apply($, someArray.map(function(item) {
    return $.ajax({...}).then(function(data){...});
})).then(function() {
    // all ajax calls done now
});


来源:https://stackoverflow.com/questions/24484601/how-to-use-promise-done-on-each-json-array-when-done-completed

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