Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain jQuery promises

I am trying to chain promises, not piping, just chaining.

For example, I have this method:

var execute = function(x){
   // this could be an AJAX call
   var d= $.Deferred();

    console.log('Begin ' + x);

    setTimeout(function(){
       console.log('End ' + x);            
       d.resolve();
    },500);

    return d;
};

And I want to execute this method a number of times, but one after the other. I have created a method that does than using eval, but I am not quite happy with using eval:

var executeTimes = function(r){
    var s = '';
    for(var i=0;i<r;i++){
        s = s + 'execute('+i+')';
        if(i!==r-1)
        s = s + '.then(function(){';
    }

    for(var i=0;i<r-1;i++){
        s= s+'})';
    }

    eval(s);
}

The idea is that doing executeTimes(3); you get this output:

Begin 0 
End 0 
Begin 1 
End 1 
Begin 2 
End 2 

I have created a live example here: http://jsfiddle.net/vtortola/Cfe5s/

What would be the best solution?

Cheers.

like image 245
vtortola Avatar asked Apr 26 '26 14:04

vtortola


1 Answers

Recursion looks neat here: http://jsfiddle.net/Cfe5s/3/.

var executeTimes = function(r) {
  (function recurse(i) {
    execute(i).then(function() {
      if(i + 1 < r) {
        recurse(i + 1);
      }
    });
  })(0);
};

You start a function that runs execute with 0, and when it's done you start over again (through recursion) but this time with 1. Before recursing, you have to check whether or not to continue: only do so when the incremented value is still lower than r.

like image 59
pimvdb Avatar answered Apr 29 '26 04:04

pimvdb