Skip to content

Instantly share code, notes, and snippets.

@cloudrain21
Last active April 8, 2016 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudrain21/45974ab35bb23456b21cda235876ece1 to your computer and use it in GitHub Desktop.
Save cloudrain21/45974ab35bb23456b21cda235876ece1 to your computer and use it in GitHub Desktop.
Use serialized or parallelized callback in nodejs
// prints text and waits one second
function doSomethingAsync(callback) {
console.log('doSomethingAsync: Wait for one second.');
setTimeout(function() { callback(); }, 1000);
}
// prints text and waits half a second
function doSomethingElseAsync(callback) {
console.log('doSomethingElseAsync: Wait for half a sec.');
setTimeout(function() { callback(); }, 500);
}
// prints text and waits two seconds
function moreAsync(callback) {
console.log('moreAsync: Wait for two seconds.');
setTimeout(function() { callback(); }, 2000);
}
// prints text and waits a second and a half
function evenMoreAsync(callback) {
console.log('evenMoreAsync: Wait for a second and a half.');
setTimeout(function() { callback(); }, 1500);
}
// prints text
function finish() { console.log('Finished.'); }
// executes the callbacks one after another
function series() {
var callbackSeries = [doSomethingAsync, doSomethingElseAsync,
moreAsync, evenMoreAsync];
function next() {
var callback = callbackSeries.shift();
if (callback) {
callback(next);
}
else {
finish();
}
}
next();
};
// run the example
series();
// execute callbacks in parallel
function parallel() {
var callbacksParallel = [doSomethingAsync, doSomethingElseAsync,
moreAsync, evenMoreAsync];
var executionCounter = 0;
callbacksParallel.forEach(function(callback, index) {
callback(function() {
executionCounter++;
if(executionCounter == callbacksParallel.length) {
finish();
}
});
});
}
// run the example
parallel();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment