英文:
Unexpected synchronous behaviour when using nodejs events module
问题
I am using Node Events module for executing my function asynchronously.
var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.on('myEvent', f2);
function f1(x, y) {
console.log('got', x, y)
eventEmitter.emit('myEvent', x, y);
eventEmitter.emit('myEvent', x, y);
eventEmitter.emit('myEvent', x, y);
console.log('done')
}
var count = 0
function f2(x, y) {
count++;
console.log('from f2', x, y, count)
}
f1(1, 2)
Its output is
alok@alok-HP-Laptop-14s-cf3xxx:~/tmp/test-node$ node alok.js
got 1 2
from f2 1 2 1
from f2 1 2 2
from f2 1 2 3
done
My expected output is
got 1 2
done
from f2 1 2 1
from f2 1 2 2
from f2 1 2 3
Why console.log('done')
is running in last. or Why execution is synchronous?
英文:
I am using Node Events module for executing my function asynchronously.
var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.on('myEvent', f2);
function f1(x, y) {
console.log('got', x, y)
eventEmitter.emit('myEvent', x, y);
eventEmitter.emit('myEvent', x, y);
eventEmitter.emit('myEvent', x, y);
console.log('done')
}
var count = 0
function f2(x, y) {
count++;
console.log('from f2', x, y, count)
}
f1(1, 2)
Its output is
alok@alok-HP-Laptop-14s-cf3xxx:~/tmp/test-node$ node alok.js
got 1 2
from f2 1 2 1
from f2 1 2 2
from f2 1 2 3
done
My expected output is
got 1 2
done
from f2 1 2 1
from f2 1 2 2
from f2 1 2 3
Why console.log('done')
is running in last. or Why execution is synchronous?
答案1
得分: 1
以下是翻译好的内容:
因为这是它的工作方式:
> 当 EventEmitter
对象触发事件时,所有附加到该特定事件的函数都会同步调用。
>
> [..]
>
> ## 异步 vs. 同步
>
> EventEmitter
以它们注册的顺序同步调用所有监听器。这确保了事件的正确排序,有助于避免竞争条件和逻辑错误。在适当的情况下,监听器函数可以使用 setImmediate()
或 process.nextTick()
方法切换到异步操作模式:
>
> const myEmitter = new MyEmitter();
> myEmitter.on('event', (a, b) => {
> setImmediate(() => {
> console.log('this happens asynchronously');
> });
> });
> myEmitter.emit('event', 'a', 'b');
>
> https://nodejs.dev/en/api/v19/events
英文:
Because that's how it works:
> When the EventEmitter
object emits an event, all of the functions attached to that specific event are called synchronously.
>
> [..]
>
> ## Asynchronous vs. synchronous
>
> The EventEmitter
calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the setImmediate()
or process.nextTick()
methods:
>
> const myEmitter = new MyEmitter();
> myEmitter.on('event', (a, b) => {
> setImmediate(() => {
> console.log('this happens asynchronously');
> });
> });
> myEmitter.emit('event', 'a', 'b');
>
> https://nodejs.dev/en/api/v19/events
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论