JavaScript is, by itβs nature within the browser, an event driven programming language. Everything starts with an event, a page is loaded, a click on a button, etc.
In NodeJs we have also the possibility to build event-listener pattern with the events module and in particular with the EventEmitter class.
Thanks to EventEmitter we can use the event-lister pattern in the backend easily. For example, suppose a system that must send a confirmation email to the users when he/she updates his profile. The update logic will reside in our domain layer and we donβt want to mess it up this layer with tasks related to send emails. With EventEmitter we can easily trigger a USER_UPDATED event and let a listener residing on another layer to make the dirty job of sending emails.
const events = require("events");
const emitter = new events.EventEmitter({ captureRejections: true });
emitter.on("emit", async () => {
console.log("listener A");
});
emitter.on("emit", async () => {
// try {
console.log("listener B");
throw new Error("dummy");
// } catch (e) {
// console.log("list B error", e);
// throw e;
// // emitter.emit("error", e);
// }
});
emitter.on("emit", async () => {
console.log("listener C");
});
emitter.on("error", e => {
console.error("== managin error", e);
});
(async () => {
try {
emitter.emit("emit");
} catch (error) {
console.log("--- managed");
console.error(error);
}
})();