function routine(){
var counter = 3;
asyncThing(function(){
// Do stuff
done();
})
asyncThing(function(){
// Do stuff
done();
})
asyncThing(function(){
// Do stuff
done();
})
function done(){
if (--counter)
return;
// Complete the routine
}
}
Above is an example of a routine that does three asynchronous sub-routines, and then completes with the done function after all asynchronous things have finished. This is using pure vanilla JavaScript. Keeping with vanilla JS, how could you improve this pattern? Are there any patterns that I'm not aware of that are arguably better?
Please provide useful discussion in the comments.
What if you wrote an ad-hoc finisher function like this:
var finisher = function(finish){
var counter = 0;
return function(f){
++counter;
return function(){
f.apply(this, arguments);
if (!--counter)
finish();
};
}
}
// Now your routine would look like this
function routine(){
var wrap = finisher(done);
asyncThing(wrap(function(){
// Do stuff
}))
asyncThing(wrap(function(){
// Do stuff
}))
asyncThing(wrap(function(){
// Do stuff
}))
function done(){
// Complete the routine
}
}
But this quickly becomes a library. Albeit a small lib, still a dependency. Thoughts?