I wrote a simple event dispatcher for my application using node's EventEmitter
I have many events and all works fine except for one, I don't know why the promises or callbacks never are completed
This is the code for dispatcher
var EventEmitter = require('events').EventEmitter,
RequireTree = require('require-tree'),
_ = require('lodash');
module.exports = {
init: function(options) {
var self = this;
_.extend(options, {
excludes: []
});
if (!options.path) {
throw new Error('You must specify the `path` option');
}
self.Emitter = self.Emitter || new EventEmitter();
// Require all files in this directory
RequireTree(options.path, {
filter: filterModels,
each: loadModels
});
function filterModels(filename) {
return options.excludes.indexOf(filename) === -1;
}
function loadModels(model) {
Object.keys(model).forEach(function(key) {
self.Emitter.on(key, model[key]);
});
}
return this;
}
};
When my application starts I call the dispatcher
dispatcher.init({
path: __dirname + '/events'
});
The event with issues
events/send_emails.jsvar Mandrill = require('mandrill-api/mandrill').Mandrill;
modules.exports = {
'send:email': function() {
var mandrill = new Mandrill('apikey', true);
var message = {
html: '<h1>Hello email</>',
from_email: 'info@example.com',
from_name: "Example",
subject: "Example mail",
to: [{
email: 'my@email.com'
}],
headers: {
'Reply-To': "info@example.com"
}
};
var cb = function(a) { console.log("PRINT SOME", a); }
mandrill.messages.send({message: message, async: false, ip_poll: 'Main Pool'}, cb, cb);
}
};
When my app emits a send:mail event, the function is called, but the PRINT SOME message never is showed in the console
I test the function send:mail in a simple script
var events = require('./events');
events['send:email']();
Calling the command
$ node test/index.js
and WORKS!!!! I saw the message PRINT SOME on the console
I don't understand what is wrong with my code with the event dispatcher
I have other events, they write files, store records on the database and call others APIs without fail
Also, I wrote a rough method using superagent for return promises
var request = require('superagent-bluebird-promise');
request
.post('https://mandrillapp.com/api/1.0/messages/send.json')
.send({message: ...}).then(..).catch(...);
the .then nor .catch methods never were called