In class which inherits EventEmitter, we usually have two points to handle error.
someClass.on('error', function eventEmitterCallback(err){/* handle error*/});
//and
someClass.someAsyncAction(function asyncActionCallback(err){/* handle error*/})
We don’t know, where error can appear, and what callback will execute.
For example, tedious (module for MS SQL Server):
- Incorrect password: both callbacks
- Incorrect database name: only
eventEmitterCallback;someAsyncActionexecute without error - Incorrect host: only
someAsyncAction - Icorrect format of host IP(for example
1234.10.0.1): node.js just down without any error 🙂
I want to create a simple function that will deligate all errors from module to first argument of callback.
function getSomeStuffFromDb(callback) {
var connection = new dbConnection(options);
connection.on('error', callback);
connection.connect(function(err) {
if (err) return callback(err);
/*exec SQL query*/
}
}
Of course, if any error cause, I want to execute callback only once.How can I make this? How correctly union two points of error handling in one? Maybe if in my class I use class that inherits EventEmmiter, I need enherits my class from EventEmitter too.
Use the
onceevent binding if you want to avoid running the same event handler over and over. Given your code sample, I don’t believeonceandonwill behave any differently because theconnectionobject is not long-lived, but it communicates the intention a touch more clearly. Then use a closure-scope flag to avoid both the event handler and callback responding to the same underlying error.