Skip to content

Instantly share code, notes, and snippets.

@WoZ
Created July 1, 2019 07:44
Show Gist options
  • Save WoZ/0f976092f75dd7a527f54280657e8080 to your computer and use it in GitHub Desktop.
Save WoZ/0f976092f75dd7a527f54280657e8080 to your computer and use it in GitHub Desktop.
event_emitter_setImmediate_example.js
const {EventEmitter} = require('events');
const ee = new EventEmitter();
function log(...args) {
console.log(Date.now() / 1000, ...args);
}
function blockingOperation() {
log('-- Blocking operation has started');
let acc = 0;
for (let i = 0; i < 1000000000; i++) {
acc += i;
}
log('-- Blocking operation has ended');
return acc;
}
ee.on('blocking-handler', message => {
log(`Blocking handler. Called inside listener: ${message}`);
blockingOperation();
});
ee.on('non-blocking-handler', message => {
log(`Blocking handler. Called inside listener: ${message}`);
setImmediate(blockingOperation);
});
function execute(event, message) {
log('Executor wants to emit message and to exit ASAP');
ee.emit(event, message);
log('Executor returns');
}
log('Begin blocking handler');
execute('blocking-handler', 'event1');
log('End of blocking handler');
console.log('-------------');
log('Begin non-blocking handler');
execute('non-blocking-handler', 'event2');
log('End of non-blocking handler');
/*
1561967007.302 'Begin blocking handler'
1561967007.305 'Executor wants to emit message and to exit ASAP'
1561967007.306 'Blocking handler. Called inside listener: event1'
1561967007.306 '-- Blocking operation has started'
1561967008.345 '-- Blocking operation has ended'
1561967008.345 'Executor returns'
1561967008.345 'End of blocking handler'
-------------
1561967008.345 'Begin non-blocking handler'
1561967008.345 'Executor wants to emit message and to exit ASAP'
1561967008.345 'Blocking handler. Called inside listener: event2'
1561967008.346 'Executor returns'
1561967008.346 'End of non-blocking handler'
1561967008.348 '-- Blocking operation has started'
1561967011.354 '-- Blocking operation has ended'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment