提问人:Hari 提问时间:5/9/2023 更新时间:5/23/2023 访问量:114
执行哪些事件循环阶段事件发射器回调?
Which event loop phase event emitter callbacks are executed?
问:
我已经开始学习节点事件循环,根据我的理解,除了回调之外,所有回调都会分阶段执行,但是当检查事件发射器回调时,它会在每个阶段执行,比如下面的代码setInterval, setImmediate, setTimeout
poll
const EventEmitter = require('events');
const fs = require('fs');
const eventEmitter = new EventEmitter();
eventEmitter.on('emit', (eventName) => {
console.log('<----- an event occurred! --->', eventName);
});
setTimeout(() => {
setTimeout(() => {
console.log(' setTimeout 0');
eventEmitter.emit('emit', 'emit inside setTimeout 0');
}, 0);
setTimeout(() => {
console.log(' setTimeout 5');
eventEmitter.emit('emit', 'setInterval inside setTimeout 5');
}, 5);
process.nextTick(() => {
console.log('process.nextTick');
eventEmitter.emit('emit', 'emit inside process.nextTick');
});
Promise.resolve().then(() => {
console.log('Promise.resolve()');
eventEmitter.emit('emit', 'emit inside Promise.resolve()');
});
setImmediate(() => {
console.log('setImmediate');
eventEmitter.emit('emit', 'emit inside setImmediate 1');
});
fs.readFile(__filename, () => {
console.log('fs.readFile');
eventEmitter.emit('emit', 'emit inside fs.readFile');
});
console.log('sync');
}, 0)
如果我打印输出,它如下所示
sync
process.nextTick
<----- an event occurred! ---> emit inside process.nextTick
Promise.resolve()
<----- an event occurred! ---> emit inside Promise.resolve()
setImmediate
<----- an event occurred! ---> emit inside setImmediate 1
setTimeout 0
<----- an event occurred! ---> emit inside setTimeout 0
setTimeout 5
<----- an event occurred! ---> setInterval inside setTimeout 5
fs.readFile
<----- an event occurred! ---> emit inside fs.readFile
一旦每个阶段都发出事件,这个事件发射器回调是如何执行的?
答:
1赞
Kaiido
#1
从节点的文档中关于:EventEmitter#emit()
按注册顺序同步调用为名为 的事件注册的每个侦听器,并将提供的参数传递给每个侦听器。
eventName
回调是同步调用的,因此它们会从调用事件循环时所处的任何阶段触发。如果你对某个特定的内置事件感到好奇,则必须在触发该事件的源中。emit()
评论