[英]Why is it that a listener to EventEmitter after a synchronous function is not executed while same works for Asynchronous function?
异步函数
import { EventEmitter } from 'events'
import { readFile } from 'fs'
class FindRegex extends EventEmitter {
constructor (regex) {
super()
this.regex = regex
this.files = []
}
addFile (file) {
this.files.push(file)
return this
}
find () {
for (const file of this.files) {
readFile(file, 'utf8', (err, content) => {
if (err) {
return this.emit('error', err)
}
this.emit('fileread', file)
const match = content.match(this.regex)
if (match) {
match.forEach(elem => this.emit('found', file, elem))
}
})
}
}
}
消耗:
const findRegexInstance = new FindRegex(/hello \w+/)
findRegexInstance
.addFile('fileA.txt')
.addFile('fileB.json')
.find()
.on('found', (file, match) => console.log(`Matched "${match}" in file ${file}`))
.on('error', err => console.error(`Error emitted ${err.message}`))
在上面的例子中,即使先调用了 find(),也会打印"Matched ... in file"
。
但是,如果重写相同的函数以使其同步:
find () {
for (const file of this.files) {
let content
try {
content = readFileSync(file, 'utf8')
} catch (err) {
this.emit('error', err)
}
this.emit('fileread', file)
const match = content.match(this.regex)
if (match) {
match.forEach(elem => this.emit('found', file, elem))
}
}
return this
}
消耗:
const findRegexSyncInstance = new FindRegexSync(/hello \w+/)
findRegexSyncInstance
.addFile('fileA.txt')
.addFile('fileB.json')
// this listener is invoked
.on('found', (file, match) => console.log(`[Before] Matched "${match}"`))
.find()
// this listener is never invoked
.on('found', (file, match) => console.log(`[After] Matched "${match}"`))
它不会输出"[After] Matched.."
消息。
我模糊地理解为什么它在同步find()
情况下不起作用。 但是,我不明白的是如何保证在 async find()
情况下始终工作?
奇怪的是,我在输入问题时找出了原因。
在同步函数调用的情况下,在同步 Find() 之后注册的任何侦听器自然不会执行,因为在侦听发生之前引发了事件。
但是在 Asynchronous Find() 的情况下, file , readFileSync 等的发现是异步发生的,并且异步发生的任何事情都会添加到事件队列中,该队列仅在当前堆栈为空后才会执行。
但是,我仍然想知道在同步 find() 的情况下是否会在第二次执行该代码段时调用在 async find() 之后注册的侦听器?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.