Skip to content

Instantly share code, notes, and snippets.

@darrenderidder
Created June 8, 2012 21:19
Show Gist options
  • Save darrenderidder/2898168 to your computer and use it in GitHub Desktop.
Save darrenderidder/2898168 to your computer and use it in GitHub Desktop.
serialize some async functions in node
var init = require('./test/common/init');
// a list of functions that we want to call, in order
var steps = [
init.createSubscriberTable,
init.clearSubscriberTable,
init.createTestSubscribers,
init.createSubscriberNoticesTable,
init.clearSubscriberNoticesTable,
init.createTestSubscriberNotices
];
// we'll be creating some specialized callbacks
var callbacks = [];
// how we create the specialized callbacks
function createCallback(index) {
return function (err, result) {
var next = steps[index+1];
var cb = callbacks[index+1];
if (err) {
console.log('Error: ' + err.message);
} else if (result) {
console.log('Result: ' + JSON.stringify(result));
}
if (next) {
next(cb);
} else {
console.log('Finished!');
process.exit(0);
}
};
}
// here we create a callback for each function in our list above
for (var i = 0; i < steps.length; i++) {
callbacks[i] = createCallback(i);
}
// now we invoke the first function with the first callback
// sit back and watch the functions execute one by one...
steps[0](callbacks[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment