将 $.when() / $.promise() 与内置 AJAX 的函数一起使用

Using $.when() / $.promise() with functions that have AJAX inside

本文关键字:函数 一起 AJAX when promise 内置      更新时间:2023-09-26
这个问题

非常困难,我知道$.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'); 
    });

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

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