Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于Events #81

Open
royIdoodle opened this issue Dec 27, 2019 · 3 comments
Open

关于Events #81

royIdoodle opened this issue Dec 27, 2019 · 3 comments

Comments

@royIdoodle
Copy link

url:https://elemefe.github.io/node-interview/#/sections/zh-cn/event-async
Events 中
有下面的描述

以及这样会不会死循环?

const EventEmitter = require('events');

let emitter = new EventEmitter();

emitter.on('myEvent', function sth () {
// 下面的代码是不是写错了?应该是 emitter.emit('myEvent')吧
  emitter.on('myEvent', sth);
  console.log('hi');
});

emitter.emit('myEvent');

能否再进一步解释一下,两种事件触发有啥区别?

@GaleLQ
Copy link

GaleLQ commented Jan 14, 2020

一个是监听里触发,一个是在监听里面监听,后者不会死循环,emit的时候相当于创建了一个原事件队列的复制去执行,再监听会加入队列,但之前的队列已经被复制好了.可以看看这里

@JianmingXia
Copy link

从 events 的文档来看,我觉得作者的代码没有写错,这里就是这么来考察的。

@cjfff
Copy link

cjfff commented Jul 21, 2021

一个是监听里触发,一个是在监听里面监听,后者不会死循环,emit的时候相当于创建了一个原事件队列的复制去执行,再监听会加入队列,但之前的队列已经被复制好了.可以看看这里

就是在 emit 执行的时候,会把之前注册好的回调列表复制副本取出执行,但是在 cb 里面继续在添加监听回调的话,会在原有的 listeners 里面继续添加,但是不会执行;因为执行的 callback list 和推入的 callbacklist 实际上内存中的引用不是同一个了.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants