I've found the following example in a book I'm reading:
function User() {
EventEmitter.call(this);
this.addUser = function (username, password) {
// add the user
// then emit an event
this.emit("userAdded", username, password);
};
}
var user = new User();
var username = "colin";
var password = "password";
user.on("userAdded", function(username, password) {
console.log("Added user " + username);
});
user.addUser(username, password);
It seems to me that using EventEmitter is completely redundant here. Promises would do a much better job:
function User() {
this.addUser = function (username, password) {
return new Promise(function (resolve) {
// add the user
// and resolve
resolve();
});
};
}
and the usage:
user.addUser(username, password).then(function(username, password) {
console.log("Added user " + username);
});
Does using EventEmitter
have any advantages over using Promises
or it's simply the code from the time when Promises where not available? Or is this style is not welcomed in node.js
?
Use event emitter if you need to notify the user of a state change. For testing purpose, if you want to make sure a function is called inside a function, emit an event.
Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.
log("event 1 fired")); // fires event1 without any data pub. emit("event1"); The neat thing about event emitters is that they are asynchronous by nature.
Main differences between EventEmitter and Promise in point, that Promise can be fulfilled only once whereas events can be triggered any number of times
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With