【问题标题】:How to use .promise().done() on $.each json array when done/completed?完成/完成后如何在 $.each json 数组上使用 .promise().done()?
【发布时间】:2014-08-20 11:57:53
【问题描述】:

我想在 $.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 来使用它吗?

【问题讨论】:

    标签: jquery promise each


    【解决方案1】:

    如您所见,$.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
    });
    

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

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

    【讨论】:

    • .map 不适用于我的情况(可能是用户错误),但 promise 数组的效果非常好。谢谢!! (抱歉死灵,但仍然有帮助)
    • 谢谢,但我不知道为什么 SO 标记 each().promise().done() 上的答案是这样的:stackoverflow.com/questions/2358205/…
    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多