I have the following problem:
I have an array with functions, that I need to call one after the other:
fun[0]() then fun[1]() ...
Since these functions make asynchronous calls, I can't just write
fun[0]();
fun[1]();
Therefore I addded at the 'end' of each function in the array a call to the next function.
This actually works, but this results in growing the stack. Example:
function fun0(){
fun[1](); // now fun[1] is added to the stack
}
Is there a way to avoid this problem? I don't need the local variables of the other functions.
Yes there is a way around.
You can use the async.js https://github.com/caolan/async
Install it using npm install async
Then if you want to execute functions one after the another, there is a method,
async.series([
function(callback){
// do some stuff ...
callback(null, 'one');
},
function(callback){
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results){
// results is now equal to ['one', 'two']
});
The second function only executes when the first one has issued the callback. Hence this makes sure all functions inside the async.series execute one after the another.
You can use
process.nextTick()
or
setInverval()
to achieve this