I am given an array of functions of length N, where every function has an asynchronous call and accepts a callback argument. The callback of function[x] is function[x+1], and function[N-1] has no callback. Here's an example of what I might be given:
function func1(callback){
$.ajax({
//Ajax settings
}).done(function(){
console.log('foo1');
if(callback) callback();
});
}
function func2(callback){
$.ajax({
//Ajax settings
}).done(function(){
console.log('foo2');
if(callback) callback();
});
}
function func3(callback){
$.ajax({
//Ajax settings
}).done(function(){
console.log('foo3');
if(callback) callback();
});
}
var funcs = [func1, func2, func3];
Am I able to build the following nested calls for the example without just building a string and calling eval():
func1(function(){
func2(function(){
func3()
})
})
/*
Output:
foo1
foo2
foo3
*/
Edit: They have to be nested because I need them to run synchronously. For-loops or foreach() create race conditions.
funcs.forEach(f => f());Promise.all, it is not the straight answer to your question, but it should fulfill your use case better