javascript - 所有事件处理程序同步触发是什么意思?

标签 javascript node.js asynchronous event-driven

我对某些术语感到困惑。我试图找出 Node.js 的事件系统实际上是如何工作的,并且在很多地方我读到事件处理程序是完全同步的。

对我来说,这似乎很奇怪,因为使用事件驱动方法的优点之一是主线程不会被事件阻塞。所以我试着想出我自己的例子,看起来发生的事情正是我真正期望的:

const fs = require('fs')
const util = require('util')
const readFile = util.promisify(fs.readFile)

const events = require('events')
const emitter = new events.EventEmitter()

emitter.on('fire', () => {
  readFile('bigFile.txt')
    .then(() => console.log('Done reading bigFile.txt'))
    .catch(error => console.log(error))
  console.log('Sync thing in handler')
})

emitter.on('fire', () => {
  console.log('Second handler')
})

console.log('First outside')
emitter.emit('fire')
console.log('Last outside')

请注意,bigFile.txt实际上是一个很大的文本文件,在我的机器上处理它需要几百毫秒。

这里我首先同步注销“Firstoutside”。然后我引发启动事件处理过程的事件。事件处理程序确实似乎是异步的,因为即使我们首先注销同步“处理程序中的同步内容”文本,我们也会开始在后台使用线程池来返回读取结果稍后再查看该文件。运行第一个处理程序后,第二个处理程序运行并打印其消息,最后我们打印出最后一条同步消息“Last Outside”。

所以我开始尝试证明一些人所说的,即事件处理程序本质上是同步的,然后我发现它们是异步的。我最好的猜测是,要么人们说事件系统是同步的意味着其他意思,要么我有一些概念上的误解。请帮助我理解这个问题!

最佳答案

EventEmitter 类与 emit 函数同步:从 .emit( 同步调用事件处理程序) 调用,正如您通过自己触发的 fire 事件所演示的那样。

一般来说,通过 Node 的事件循环来自操作系统(文件和网络操作、计时器等)的事件是异步触发的。您自己不会触发它们,某些 native API 确实会触发它们。当您收听这些事件时,您可以确定 they will occur not before the next tick .

The event handler does seem to be asynchronous, because even though we first log out the synchronous 'Sync thing in handler' text, we start using the thread pool in the background to return back with the result of reading the file later

是的,您正在调用异步函数readFile(稍后会通知您),但这不会使您的事件监听器函数或.emit('fire') 异步调用。即使启动后台进程的“异步函数”也会立即(同步)返回一些东西 - 通常什么也没有(未定义)或一个 promise 。

关于javascript - 所有事件处理程序同步触发是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65043301/

相关文章:

node.js - 用户 : anonymous is not authorized to perform: es:ESHttpPost on resource:

python - Python Asyncio队列获取未收到消息

javascript - ddslick 值未定义 - 无法传递值

javascript - 如何防止 dynamicMapLayer 在每次缩放或平移 map 时刷新?

javascript - 下拉菜单 - 在父窗口中打开链接

node.js - 当我运行 "npm run dist_win"时,收到错误 : "node_modules" Not an internal or external command?

node.js - 使用 Multer 未将图像文件名插入到数据库中

java - ServerInterceptor 中的 grpc-java 异步调用

javascript - 使用 JavaScript 异步代替 setInterval

javascript - 使用辅助监视器时,如何在 window.onmousemove 上获取相对于主屏幕的 e.screenX/Y?