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.
Recursion looks neat here: http://jsfiddle.net/Cfe5s/3/.
You start a function that runs
executewith0, and when it’s done you start over again (through recursion) but this time with1. Before recursing, you have to check whether or not to continue: only do so when the incremented value is still lower thanr.