0

What is the proper way to get 'poof1' event without timeouts? Now it's only 'poof2' fires up.

function Em(cfg){
    let event = new EventEmitter();

    event.emit('poof1');

    setTimeout(() => {
        event.emit('poof2');
    }, 1000);

    return event;
}

let em = new Em();
em.on('poof1', () => {
    console.log('event 1');
});

em.on('poof2', () => {
    console.log('event 2');
});
John Lenson
  • 167
  • 2
  • 9

1 Answers1

0

you're attaching poof1 listener (.on) after you emit the event (.emit)

the one wrapped inside the timeout is working because is delayed giving the time to the listener to be attached.

try to refactor a little bit your code

let em = new EventEmitter();
em.on('poof1', () => {
    console.log('event 1');
});

em.on('poof2', () => {
    console.log('event 2');
});

event.emit('poof1');
event.emit('poof2');
Karim
  • 8,454
  • 3
  • 25
  • 33
  • But what if I want to keep this structure? let em = new Em(); em.on('poof1', () => {}); em.on('poof2', () => { }); – John Lenson Oct 25 '17 at 07:31
  • i don't get the sense of the EM function, you have a cfg parameter that you're not using. you can change my code as you want but you have to declare the listeners before you emit the event otherwise there's no chance your listeners will catch the events – Karim Oct 25 '17 at 07:43