Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
Anna K. Avatar asked Oct 20 '25 11:10

Anna K.


1 Answers

But the number of ajax calls depends on the arguments that I pass to the function, which is an array

If it's one ajax call per array item

function do_ajax_calls(args) {
    return args.reduce(function(promise, item) {
        return promise.then(function() { 
            return $.ajax(args); // should that be item?
        });
    }, Promise.resolve(true));
}

The Promise.resolve(true) is a "native" promise, i.e. not available in IE, but I'm sure jQuery has an equivalent

Here's a JSFiddle Demo

like image 88
Jaromanda X Avatar answered Oct 23 '25 00:10

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!