0

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

2
  • 3
    As instructed in How to Ask, please describe your problem before showing code. Commented Jan 6, 2023 at 8:53
  • 1
    You can't make any long running synchronous function be asynchronous. You can affect the timing of when it runs using setImmediate(), setTimeout() or process.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. Commented Jan 6, 2023 at 8:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.