This question already has answers here:
$.Deferred: How to detect when every promise has been executed

(3个答案)


4年前关闭。




我发送多个承诺以使用ajax获取用户详细信息。

var a= APP.request('user:getID');//Promise request
var b= APP.request('user:getName');//Promise request
var c= APP.request('user:getNumber');//Promise request
var d= APP.request('user:getAge');//Promise request
$.when(a.done(), b.done(), c.done(), d.done()).done(function() {
    console.log("Saving to single view.");//Working fine when ajax url is up.not working if any one url goes down.
}


如果所有网址都打开,这将起作用。
但是,如果任何一个URL都已关闭,则在阻止时它不会进入内部。

我只是修改了代码,然后又引入了同样的问题。

$.when(a.then(), b.then(), c.then(), d.then()).then(function() {
    console.log("Saving to single view.");
}


我无法弄清楚我的代码有什么问题。

更新:我必须在所有的诺言被执行后才执行$ when块。

最佳答案

我成功地运用了一系列承诺

var finalCheck = [];


然后.push()

finalCheck.push( APP.request('user:getID') ) ;  //Promise request
finalCheck.push( APP.request('user:getName'));  //Promise request
finalCheck.push( APP.request('user:getNumber'));//Promise request
finalCheck.push( APP.request('user:getAge'));   //Promise request


您可能会或不会从将某些逻辑移至Defferred函数中受益。我之所以喜欢这样,是因为在失败的子请求恢复/回退之后,我必须执行该工作,这使得该方法可从多个位置使用。这里重要的部分是Defferred函数位于$.when.apply()之前。

var AfterAllRequests = $.Deferred().done(function () {
             // real final work here...
             console.log("Saving to single view.");
        });


并等待这些诺言的成败

$.when.apply($, finalCheck).done(function () {
            AfterAllRequests.resolve();
        }).fail(function () {
            console.log(" Some GET(s) failed, handle fallback content ...");
            // ....
            AfterAllRequests.resolve();
        });


未经测试的变体-您可以尝试使用.always()而不是.done().fail(),但是我(um)总是有不同的事情要做,具体取决于承诺组的成败。它看起来像:

$.when.apply($, finalCheck).always(function () {
           // well now it is time....and you may not need a deferred anymore
            AfterAllRequests.resolve();
        });

关于jquery - 具有多个promise的jQuery ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31314500/

10-11 20:03
查看更多