Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send response and continue to perform tasks Express | Node.js

Tags:

People also ask

How do I send response back in node JS?

Methods to send response from server to client are:Using send() function. Using json() function.

Which method sends response data in Express?

send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array. Parameter: This function accepts a single parameter body that describe the body which is to be sent in the response.

What does Express () method do?

Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.

What does next () do in Express?

The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.


In Node.js (which I'm new to) I am trying to perform a series of tasks after receiving a response. However, I want to make the response time as fast as possible. I don't need to return the results of these tasks to the client, so I'm trying to return the response immediately.

My current implementation is roughly:

var requestTime = Date.now;   app.post('/messages', function (req, res) {   console.log("received request");    // handle the response   var body = res.body;   res.send('Success');   res.end();   console.log("sent response");    performComplexTasks(body) })  function performComplexTasks(body){    // perform data with body data here;    console.log("finished tasks:", Date.now()-requestTime, "ms"); }  // -------LOG----------- //    received request //    POST /api/messages 200 3.685 ms - 59 //    sent response //    finished tasks: 2500ms 

The client making the request seems to hang until performComplexTasks() is finished. (The POST finishes in 3.685ms, but the response takes 2500ms to finish.)

Is there a way to send the response immediately and complete other tasks without having the client wait/hang? (In my case, the client cannot make multiple API calls.)