Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run background task in node.js api after sending response?

I have a requirement, where i have to run a one minute background process after returning the response for an api. That background process will do some operation on mongodb.

My approach is, i am emitting an event for background process after returning the response.

Is there any best approach to this operation? Please help me.

Thanks,

like image 928
aaqib90 Avatar asked Mar 06 '18 19:03

aaqib90


1 Answers

You could use an EventEmitter to trigger the background task.

Or you can trigger an asynchronous task before you return the response.

I would implement some kind of simple in-memory queue. Before returning the response I would add a task to the queue, emit an event telling listeners there is task in the queue.

Edit:

I'm not sure if I understand your use case exactly. But this might be one approach.

If you do not have reference to do the mongo you might have to do some fast lookup or creation, then return the response, then run the task

const myqueue = []

const eventHandler = new EventEmitter();

eventHandler.on('performBackgroundTask', () => {

  myqueue.forEach(task => {
    // perform task
  })

})

app.get('/api', function (req, res) {

    const identificationForItemInMongo = 123

    myqueue.push(identificationForItemInMongo)

    eventHandler.emit('performBackgroundTask',     identificationForItemInMongo)

   res.send('Send the response')
})
like image 97
Khlbrg Avatar answered Oct 24 '22 17:10

Khlbrg