In my API I want to execute long running function call in background and I dont want to use any task queue like RabbitMQ.
I am trying to run long running function using events module of Node. But 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.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.
const express = require('express')
var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.on('scream', ()=>{
setImmediate(longRunningFunction)
});
const app = express()
const port = 3000
function longRunningFunction() {
let count = 0
for (let i=0; i<1000000000; i++) {
count++
}
console.log('done')
return count
}
app.get('/', (req, res) => {
let start = Date.now()
eventEmitter.emit('scream');
let end = Date.now()
res.send(`Hello World!: ${end-start}`)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
How to make event listener run asynchronously in events module of Node without using setImmediate() or process.nextTick() ?
setImmediate(),setTimeout()orprocess.nextTick(), but when it runs, it will still be synchronous and blocking. If you truly want to get it out of the main event loop so it doesn't block the event loop, then put it in a WorkerThread or a child_process and communicate back its result via messaging. Javascript in nodejs runs your Javascript in a single thread, so any synchronous, long running code will be blocking, no matter when you run it.