Anna K. Anna K. - 4 years ago 177
Javascript Question

Multiple jQuery promises in sequential order

Basically I want this:

function do_ajax_calls(...){
var d = $.Deferred();

$.ajax(args).done(function(){

$.ajax(args).done(function(){

$.ajax(args).done(function(){
d.resolve();
});

});

})

return d.promise();
}


But the number of ajax calls depends on the arguments that I pass to the function, which is an array, so I can't use that code.

The function should return a promise that only resolves when the last ajax calls completes. So the function needs to be called like this:

do_ajax_calls(....).done(function(){
// here is the callback
})


Does anyone know how can I do this?

Answer Source

One of the reasons promises are a big deal is because they can be chained. You can use this to your advantage to iteratively chain additional requests onto the resolution of the previous one:

function do_ajax_calls() {
    var dfd = $.Deferred();
    var promise = dfd.promise();
    var responses = [];

    function chainRequest(url) {
        promise = promise.then(function (response) {
            responses.push(response);
            return $.ajax(url, { method: 'POST' });
        });
    }

    for (var i = 0, length = arguments.length; i < length; i++) {
        chainRequest(arguments[i]);
    }

    dfd.resolve();

    return promise.then(function (response) {
        return responses.slice(1).concat(response);
    });
}

The above code will return a promise ultimately resolving to an array of all of the responses. If any one of the requests fails, the promise will reject with the first failure.

JSFiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download