Created
June 8, 2012 21:19
-
-
Save darrenderidder/2898168 to your computer and use it in GitHub Desktop.
serialize some async functions in node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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