將一組延遲傳遞給 $.when() - Pass in an array of Deferreds to $.when()

問題:

Here's an contrived example of what's going on: http://jsfiddle.net/adamjford/YNGcm/20/這是一個人爲的例子: http : //jsfiddle.net/adamjford/YNGcm/20/

HTML: HTML:

<a href="#">Click me!</a>
<div></div>

JavaScript: JavaScript:

function getSomeDeferredStuff() {
    var deferreds = [];

    var i = 1;
    for (i = 1; i <= 10; i++) {
        var count = i;

        deferreds.push(
        $.post('/echo/html/', {
            html: "<p>Task #" + count + " complete.",
            delay: count
        }).success(function(data) {
            $("div").append(data);
        }));
    }

    return deferreds;
}

$(function() {
    $("a").click(function() {
        var deferreds = getSomeDeferredStuff();

        $.when(deferreds).done(function() {
            $("div").append("<p>All done!</p>");
        });
    });
});

I want "All done!"我要“全部完成!” to appear after all of the deferred tasks have completed, but $.when() doesn't appear to know how to handle an array of Deferred objects.在所有延遲任務完成後出現,但$.when()似乎不知道如何處理延遲對象數組。 "All done!" “全部完成!” is happening first because the array is not a Deferred object, so jQuery goes ahead and assumes it's just done.因爲數組不是 Deferred 對象,所以首先發生,所以 jQuery 繼續並假設它剛剛完成。

I know one could pass the objects into the function like $.when(deferred1, deferred2, ..., deferredX) but it's unknown how many Deferred objects there will be at execution in the actual problem I'm trying to solve.我知道可以將對象傳遞給像$.when(deferred1, deferred2, ..., deferredX)這樣的函數$.when(deferred1, deferred2, ..., deferredX)但不知道在我試圖解決的實際問題中將有多少 Deferred 對象在執行。


解決方案:

參考一: https://en.stackoom.com/question/Nbue
參考二: https://stackoom.com/question/Nbue
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章