Skip to content

Instantly share code, notes, and snippets.

@DiegoVictor
Last active May 15, 2021 23:13
Show Gist options
  • Save DiegoVictor/702da4ae9d1f1e3d05b6a659b3d878ca to your computer and use it in GitHub Desktop.
Save DiegoVictor/702da4ae9d1f1e3d05b6a659b3d878ca to your computer and use it in GitHub Desktop.
How to use Node.js EventEmmiter
// https://nodejs.org/api/events.html
const EventEmmiter = require("events");
const eventEmmiter = new EventEmmiter();
const cooking = async ({ name }) => ({ name });
const driveTo = async () => true;
const leave = async () => ({ delivered: true });
async function cook({ pizzaOrder, user }) {
console.log(`Cooking a ${pizzaOrder.name}`);
return cooking(pizzaOrder).then((pizza) => {
console.log(`The ${pizza.name} is ready! In time to deliver!`);
eventEmmiter.emit("deliver", { address: user.address, pizza });
});
}
async function deliver({ pizza, address }) {
console.log(`Driving to ${address}`);
return driveTo(address).then(() => {
console.log(`Delivering the ${pizza.name} at ${address}`);
return leave(pizza);
});
}
eventEmmiter
.on("order", (details) => {
console.log("A new pizza order arrived");
cook(details);
})
.on("deliver", async ({ address, pizza }) => {
console.log("Calling delivery man!");
deliver({ pizza, address }).then(({ delivered }) => {
if (delivered) {
console.log("Close order");
} else {
console.log("Ops! The pizza was not delivered");
}
});
});
eventEmmiter.emit("order", {
pizzaOrder: {
quantity: 1,
name: "Master Pizza",
description: "Provolone, Green Olives, Green Peppers",
},
user: {
address: "682 Cheyenne Stream",
},
});
// A new pizza order arrived
// Cooking a Master Pizza
// The Master Pizza is ready! In time to deliver!
// Calling delivery man!
// Driving to 682 Cheyenne Stream
// Delivering the Master Pizza at 682 Cheyenne Stream
// Close order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment