Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use `eventEmitter` instead of promise

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?

like image 307
Max Koretskyi Avatar asked Dec 14 '16 10:12

Max Koretskyi


People also ask

Why do we use EventEmitter?

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.

Why do we use EventEmitter in NodeJS?

Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.

Is EventEmitter asynchronous?

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.


1 Answers

Main differences between EventEmitter and Promise in point, that Promise can be fulfilled only once whereas events can be triggered any number of times

like image 119
Denis Lisitskiy Avatar answered Sep 20 '22 02:09

Denis Lisitskiy