Max Koretskyi
Max Koretskyi

Reputation: 105563

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?

Upvotes: 6

Views: 2009

Answers (2)

Mario
Mario

Reputation: 1

I do not understand in which scenario it becomes reality what Denis wrote. Each time addUser is called, a new promise is returned. In event driven logic a new event is triggered. Main difference I see is that a promise, whilst more performant (in my experience), is sort of "local". You have singular linear path from where method was called. Meanwhile when using events, you can have multiple other components listen to the event. So each time a user gets added, all of them get notified and run their logic. Another thing is that with events you can define what happens once and then no matter where the method which triggers the event is called, the event listener callback fires.

Upvotes: -1

Denis Lisitskiy
Denis Lisitskiy

Reputation: 1345

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

Upvotes: 10

Related Questions