Methods to send response from server to client are:Using send() function. Using json() function.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With