Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why this code is only printing the first statement as output

var events = require('events')
var eventEmitter = new events.EventEmitter();

var fn1 = function() {
  console.log("first fn executed on triggering first event  ")
  eventEmitter.emit('fn1')
}
eventEmitter.on("event1", fn1)
eventEmitter.emit('event1')
eventEmitter.on('fn1', function() {
  console.log("This is the fn triggered on 2nd event")
})

output on executing it by node event1.js is
" first fn executed on triggering first event "

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Because the handler is registered after the event is fired. Try this:

var events = require('events')
var eventEmitter = new events.EventEmitter();

var fn1 = function() {
    console.log("first fn executed on triggering first event  ")
    eventEmitter.emit('fn1')
}
eventEmitter.on("event1", fn1)

eventEmitter.on('fn1', function() {
    console.log("This is the fn triggered on 2nd event")
})
eventEmitter.emit('event1')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading