Pass in an array of Deferreds to $.when()

后端 未结 9 1239
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:20

Here\'s an contrived example of what\'s going on: http://jsfiddle.net/adamjford/YNGcm/20/

HTML:

Click me!
&l
9条回答
  •  死守一世寂寞
    2020-11-21 22:39

    As a simple alternative, that does not require $.when.apply or an array, you can use the following pattern to generate a single promise for multiple parallel promises:

    promise = $.when(promise, anotherPromise);
    

    e.g.

    function GetSomeDeferredStuff() {
        // Start with an empty resolved promise (or undefined does the same!)
        var promise;
        var i = 1;
        for (i = 1; i <= 5; i++) {
            var count = i;
    
            promise = $.when(promise,
            $.ajax({
                type: "POST",
                url: '/echo/html/',
                data: {
                    html: "

    Task #" + count + " complete.", delay: count / 2 }, success: function (data) { $("div").append(data); } })); } return promise; } $(function () { $("a").click(function () { var promise = GetSomeDeferredStuff(); promise.then(function () { $("div").append("

    All done!

    "); }); }); });

    Notes:

    • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
    • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested inside additional objects). For what you want though it is short and simple.
    • The upside is it requires no array or array management.

提交回复
热议问题