Eventemitter and nexttick in nodejs

后端 未结 1 526
执念已碎
执念已碎 2021-01-27 05:36

I\'m confused about Eventemitter. I write a code but that does not work properly. Why the below code does not work :

const EventEmitter = require(\'events\');
co         


        
相关标签:
1条回答
  • 2021-01-27 05:56

    EventEmitter emits synchronously, which means that in your first example, the event being emitted (from the constructor) is emitted before a listener has been attached. Because events aren't queued or "saved", your event listener won't get the message (it simply started listening too late).

    In your second example, the event is emitted from the constructor in the next cycle of the event loop (asynchronously). At that point, the code that adds the listener to myEmitter has already run, so at the time the event is being emitted the listener will receive it.

    It's similar to this:

    // synchronously: 'A' is logged before 'B'
    console.log('A');
    console.log('B');
    
    // asynchronously: 'B' is logged before 'A'
    process.nextTick(function() { console.log('A') });
    console.log('B');
    
    0 讨论(0)
提交回复
热议问题