import { on, EventEmitter } from 'node:events';
import process from 'node:process';
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
console.log('Unreachable here');
i was expecting ‘Unreachable here’ to be logged as well, but it didn’t,
What could be causing the script to exit prematurely after the for await…of loop completes? How can I modify this code to ensure that ‘Unreachable here’ is logged after the event processing completes?
2
Answers
Did you reach the console.log(event);? I asume you did since you only mentioned not reaching the end of the code. If you didn’t however your condition might never be true. In that case check if the await happens before the actual ee const is defined.
if you do reach that code maybe the loop is infinit. And becouse await lets the code wait for the function to be executed it never continues. I hope this was somewhat helpfull.
As far as I know
await
waits for a Promise to be fulfilled.Since you await
on()
you never fulfill such Promise and wait forever.You could try an async approach like this instead of the for loop:
With that your Code can run through and each event will trigger the code inside the callback function.