【问题标题】:Using $.when() / $.promise() with functions that have AJAX inside将 $.when() / $.promise() 与内部具有 AJAX 的函数一起使用
【发布时间】:2013-01-31 21:15:01
【问题描述】:

这个问题真的很难解决,我知道 $.when() 可以像这样使用(带有多个 AJAX 语句)来向您保证它们都完成了。

http://jsfiddle.net/M93MQ/

    $.when(
        $.ajax({ url: '/echo/html/', success: function(data) {
            alert('request 1 complete')
          }
        }),

        $.ajax({ url: '/echo/html/', success: function(data) {
            alert('request 2 complete')
          }
        })
    ).then( function () { alert('all complete'); });

但这仅适用于原始$.ajax(),是否有同样的功能带有函数调用,而其中又包含 ajax(和其他随机逻辑)?

伪代码思路:

    // The functions having the AJAX inside them of course
    $.when(ajaxFunctionOne, ajaxFunctionTwo).then(function () {
        alert('all complete'); 
    });

【问题讨论】:

  • 您传递给$.when() 的是对$.ajax 进行的函数调用的返回值;换句话说,你没有传递它的功能。在调用$.when() 时,ajax 操作已经开始。

标签: javascript ajax jquery jquery-deferred


【解决方案1】:

当然,让函数返回一个承诺对象。

function ajaxFunctionOne() {
    return $.ajax(...)
}
function ajaxFunctionTwo() {
    var dfd = $.Deferred();
    // on some async condition such as dom ready:
    $(dfd.resolve);
    return dfd.promise();
}

function ajaxFunctionThree() {
    // two ajax, one that depends on another
    return $.ajax(...).then(function(){
        return $.ajax(...);
    });
}   

$.when(ajaxFunctionOne(),ajaxFunctionTwo(),ajaxFunctionThree()).done(function(){
    alert("all complete")
});

【讨论】:

  • 太棒了...谢谢凯文,我是个假人,我没有调用$.when(functionName <-- no () 中的函数,而且我不知道它必须在return 中它!立即清除它,你的男人现在dawg。
猜你喜欢
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多