In Express.js I want to perform a task after send a response.
However, I want to make the response time as fast as possible. I don't need to return the results of this tasks to the client, so I'm trying to return the response immediately.
The task isn't CPU-intensive, then event loop isn't locked by that task.
So, this is my background task:
function backgroundTask() {
return new Promise(resolve => setTimeout(() => {
console.log("backgroundTask finished");
resolve();
}, 1000));
}
My first attemp is to call backgroundTask function directly:
app.post('/messages', async function (req, res) {
res.status(200).send({ success: true });
performBackgroundTasks();
});
the second attemp is to call backgroundTask function into a setTimeout():
app.post('/messages', async function (req, res) {
res.status(200).send({ success: true });
setTimeout(() => performBackgroundTasks(), 0);
});
The question is: what is the best method for ensecure that the response is send to the client and the task is berformed in the background?
SIDE NOTE: i know that the "best method" is use Worker Threads, but i just need a simple way for perform a background task.