'Handling long running database calls in nodejs

I have an endpoint which send out response to client and based on response I want to do database calls(creating data of users)? How to achieve this after sending out response?

router.post('/',(req,res) => {
  Policy.findOneAndUpdate({ _id: id, isActive: true }, { $set: req.body }, { new:true })
 .then(result => {
      // here i do not want to block the client so sending response
      res.status(200).json({message: 'Action taken Successfully'})
     /* After policy gets approved, My task here is to fetch all the list of 
        users and create data(policy data) for them so that they can fetch the policies and take action. */
})


Solution 1:[1]

Of course you can call it asynchronously. Just call it before/after sending the response. But you can't send the headers again, it will generate errors.

Try the following code:

router.post('/', (req, res) => {
    Policy.findOneAndUpdate({ _id: id, isActive: true }, { $set: req.body }, { new:true })
        .then(result => {
            res.status(200).json({message: 'Action taken Successfully'});
            your_function_to_execute_other_operations();
        });
});

The above code will immediately send response after executing the res.send. After that, it will take care of the your_function_to_execute_other_operations function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sherin Jose