NodeJS 执行哪些事件循环阶段事件发射器回调?

irtuqstp  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(147)

我已经开始学习节点事件循环,根据我的理解,除了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

如何在每个阶段发出事件后立即执行此事件发射器回调?

zpgglvta

zpgglvta1#

从node的文档关于EventEmitter#emit()
同步调用为名为eventName的事件注册的每个侦听器,按照它们注册的顺序,向每个侦听器传递提供的参数。
回调被同步调用,因此它们是从调用emit()时事件循环所处的任何阶段触发的。如果您对某个特定的内置事件感到好奇,则必须查看触发该事件的源代码。

相关问题