node.js execute function after 'n' async callback are executed
asynchronous, callback, events, node.js
Solution
I would suggest using an async library such as Caolan's Async. Then, you can use `async.parallel`, `async.series`, or `async.auto`. `auto` is the most flexible, but a bit slower than the others; choosing between `parallel` and `series` would require more information on what you're trying to do - your first example would be a parallel operation, but your second example is in series.
However, if you don't want to use a library, you can write something custom. I would do it as follows:
var numFuncs = 4;
var callback = function(){
numFuncs--;
if(numFuncs == 0) {
after4AsyncOperation();
}
}
var after4AsyncOperation = function(){
//do something...
}
process.nextTick(function(){
//do stuff
callback();
})
process.nextTick(function(){
//do stuff
callback();
})
process.nextTick(function(){
//do stuff
callback();
})
process.nextTick(function(){
//do stuff
callback();
})
This works by counting down from the number of times we expect the callback to be called (`numFuncs`) and only calling `after4AsyncOperation` when we've been called back the right number of times.
Problem
I can't get how can I execute a callback after 'n' async functions are executed, example: ``` var after4AsyncOperation = function(){ //do something... } process.nextTick(function(){ //do stuff }) process.nextTick(function(){ //do stuff }) process.nextTick(function(){ //do stuff }) process.nextTick(function(){ //do stuff }) ``` Is there a way to execute `after4AsyncOperation` after the 4 async functions without have to write the function one inside the other, ex: ``` var after4AsyncOperation = function(){ //do something... } process.nextTick(function(){ //do stuff process.nextTick(function(){ //do stuff process.nextTick(function(){ //do stuff process.nextTick(function(){ //do stuff after4Asyncoperation(); }) }) }) }) ```