I'm working my way through Smashing Node.js, which seems great so far, but there's something about writing async code and using callbacks that I don't understand.
If I have code like this:
myObject.doSomethingAsync( errorCallback );
// all done, want to exit here, but errorCallback may be called
…
function errorCallback(args) {
// do something that takes a few seconds
}
Keep in mind that I do mean exit; this is a scheduled task not a server.
How do I know when to exit? It'd be easier if errorCallback was always called, but in the case of one module I'm using, it's not. Is it odd to have this kind of conditional callback? How do I handle this cleanly?
The convention in Node is for callbacks to accept an Error object as the first argument.
http://blog.gvm-it.eu/post/22040726249/callback-conventions-in-node-js-how-and-why
Your callback should get called on both success and failure. On success the err object will be null.
Of course this is the convention, but there are probably plenty of modules that disregard this convention. You should either attempt to fix the module you are using or use a different one.
Node will exit the process when nothing is left to do. If you need to do something before the exit occurs you can listen for process.exit.