jquery - 完成/完成后如何在 $.each json 数组上使用 .promise().done() ?

标签 jquery promise each

我想在 $.each 完成后执行一些操作。

$.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
  • 并非每个 jQuery 函数都有 promise()
  • 我如何知道 $.each 数组何时完成?
  • 我可以将 someArray 更改为 $someArray 来使用它吗?

最佳答案

正如您所发现的, $.each() 没有 .promise() 所以您无法按照您尝试的方式进行操作到。相反,您可以使用 $.when() 来跟踪一组 Ajax 函数返回的一堆 Promise 何时全部得到解析:

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

或者,使用 .map() 比使用 $.each() 更简洁:

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

关于jquery - 完成/完成后如何在 $.each json 数组上使用 .promise().done() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24484601/

相关文章:

javascript - 清理 promise (扁平化和错误处理)

JQuery 使用each()作为每个循环的经典,而不是一次全部循环

javascript - 使用 javascript 和 jquery 进行回调

jQuery-UI 在没有 CSS 或自定义的情况下无法在我的用户脚本中工作?

database - Knex promise 交易

javascript - Angular 返回 promise

jQuery .each 循环与简单的数学不给出单独的结果

ruby - 遍历 Ruby 数组最惯用的方法,满足任意条件时退出?

c# - 将字符串转换为日期时间-javascript

javascript - 通过ajax提交选择框的值并显示结果不起作用