Use EventEmitter in ES6 class

冷暖自知 提交于 2019-12-04 22:35:45

Events are synchronous - you're firing it before you are listening. Use

const testClient = new Client(1,2,3,4,5);
testClient.on('event', () => {console.log('triggered!')} );
testClient.eventTest();
user3674318

You could use process.nextTick() to make you code asynchronous. Afterwards everything will work as expected. This is the note from the node documentation:

The process.nextTick() method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.

eventTest(){
    process.nextTick(() => {
        this.emit("event");
    });
    console.log(this.token);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!