Created
July 4, 2018 09:02
-
-
Save goldbergyoni/d14f7158202ab3bf764020294b1b0737 to your computer and use it in GitHub Desktop.
Realtime event emitters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const EventEmitter = require("events"); | |
| class Session extends EventEmitter { | |
| constructor(id) { | |
| super(); | |
| this.id = id; | |
| } | |
| start() { | |
| console.log(`Session is about to start ${this.id}`); | |
| const howLongToRun = Math.ceil(Math.random()*5); | |
| setTimeout(() => { | |
| this.emit("end", this.id); | |
| }, howLongToRun*1000); | |
| } | |
| } | |
| class Scheduler { | |
| start() { | |
| [1, 2, 3].forEach((item) => { | |
| const session = new Session(item); | |
| session.on('end', (id) => { | |
| console.log(`Scheduler was notified that session has finished ${id}`); | |
| }); | |
| session.start(); | |
| console.log(`Scheduler just started session ${item}`) | |
| }) | |
| } | |
| } | |
| new Scheduler().start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment