Created
December 29, 2018 07:28
-
-
Save rmar72/08aa2681cb63bf2c920db6bc1b6ac2c0 to your computer and use it in GitHub Desktop.
Practicing with Node.js 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
// 10/25/2018 | |
// Node practice from docs | |
//----- Experimenting with event emitters! | |
const EventEmitter = require('events'); | |
class MyEmitter extends EventEmitter {} | |
const myEmitter = new MyEmitter(); | |
myEmitter.on('myevento', () => { | |
console.log('an evento occurred!'); | |
}); | |
// goes second | |
setTimeout(()=>{ | |
console.log(2.5) | |
myEmitter.emit('myevento'); | |
}, 3000); | |
// goes first | |
process.nextTick( () => { | |
console.log("next loop iteration 2") | |
myEmitter.emit('myevento'); | |
// goes third | |
setTimeout(()=>{ | |
console.log(3) | |
myEmitter.emit('myevento'); | |
}, 3000); | |
}) | |
//----- passing args to event.emit | |
const myEmitter2 = new MyEmitter(); | |
myEmitter2.on('event', function(a, b) { | |
console.log(a, b, this === myEmitter2, this); | |
// Prints: | |
// a b true MyEmitter { | |
// domain: null, | |
// _events: { event: [Function] }, | |
// _eventsCount: 1, | |
// _maxListeners: undefined } | |
}); | |
myEmitter2.emit('event', 'a', 'b'); | |
class myEmitter3 extends EventEmitter {}; | |
console.log("\n" + Object.getPrototypeOf(myEmitter3)) //[Function: EventEmitter] | |
// ----- Async Emitters | |
// up until this point I've used sync emitters, sure I called them async by wrapping the invokation within aysnc fn's | |
// but to avoid race conditions or logic errors here is an async emitter | |
const myEmitter4 = new MyEmitter(); | |
myEmitter4.on("evt4", (a, b) => { | |
setImmediate(()=>{ | |
console.log("this happens async") | |
}); | |
}); | |
myEmitter4.emit("evt4"); | |
// ----- Handling events only once | |
const myEmitterr = new MyEmitter(); | |
let m = 0; | |
myEmitterr.once('event', () => { | |
console.log("m value: ", ++m); | |
}); | |
myEmitterr.emit('event'); | |
// Prints: 1 | |
myEmitterr.emit('event'); | |
// Ignored | |
// ----- Error handling | |
//const myEmitteer = new MyEmitter(); | |
//myEmitteer.emit('error', new Error('whoops!')); | |
// Throws and crashes Node.js | |
// As a best practice, listeners should always be added for the 'error' events. | |
// keeps app running w/out crashing | |
const myEmittter = new MyEmitter(); | |
myEmittter.on('error', (err) => { | |
console.error('whoops! there was an error'); | |
}); | |
myEmittter.emit('error', new Error('whoops!')); | |
// Prints: whoops! there was an error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment