Deferred Example 3

The third is the same as the second except it's encapsulated into a "worker" which, like the second one, keeps doing the next thing in the queue until its empty then triggers a deferred

by someprimetime

JavaScript

var urls = [];

//Make a bunch of URLs, use delay= to make them take time to load.
for (var i = 0; i < 10; i++) {
    var n = Math.floor(Math.random() * 2);
    urls.push("http://jsfiddle.net/echo/jsonp/?delay=" + n + "&data=" + i);
}

var index = 0;

function worker(id) {
    var alldone = $.Deferred();

    //Do the next piece of work to be done.
    //This can be starting a new AJAX request or triggering the
    //final "alldone" deferred.

    function next() {
        if (index >= urls.length) {
            log(id + ": Finished my work");
            alldone.resolve();
            return;
        }

        var i = index++;

        log(id + ": Starting number " + i);
        $.ajax({
            url: urls[i],
            dataType: "jsonp",
            success: function() {
                log(id + ": Finished number " + i);
            }
        }).done(next);
    }

    //Start the first one
    next();

    return alldone;
}

worker("A").done(function() {
    log("Last one finished!");
});





function log(msg) {
    $("<div>", {
        text: msg
    }).appendTo("body");
}