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() ?

0

There are 0 best solutions below