*Note: Re-writing question:
I am trying to write the following outside of the individual function calls:
example:
function f1(){
I had this problem recently. If you have a bunch of functions that do async stuff, just make them all to return a Deferred, which you manually resolve when the function async job is finished. Then you can put the functions in an array and run them sequentially:
// Sample asynchronous function that returns Deferred
var f = function(name){
console.log('Function root start', name);
var d = $.Deferred();
d.done(function(result){
console.log('Async work finish', name, result);
});
setTimeout(function(){
setTimeout(function(){
d.resolve('Hello');
}, 200);
}, 1000);
console.log('Function root finish', name);
return d;
};
// Array with functions
var defs = [];
defs.push(f.bind(null, 1));
defs.push(f.bind(null, 2));
defs.push(f.bind(null, 3));
// Recursive sequential calling
var i = 0;
var runAtIndex = function (i) {
i < defs.length && defs[i]().done(function() { runAtIndex(i + 1); });
}
runAtIndex(i);