I am writing a application in Node.js I need some suggestion.
I get a POST request from client. After I receive a request I call some functions. At the end of execution I need to reply back to the client which initiated the request using HTTP response. Issues are:
How do I go about it? Can I get some architectural suggestions?
It sounds like you want to use something like the async library to handle your asynchronous tasks (either async.series or async.parallel sounds appropriate).
That way, you can 'group' all your asynchronous tasks and have one single callback which is called when all tasks are finished. From that callback you can handle your response:
app.post('/your/route', function(req, res) {
async.parallel([
// start your tasks (called 'task1', 'task2', and pass the 'async' callback
// to them; once a task is done, it needs to call the callback)
function(cb) { task1(cb); },
function(cb) { task2(cb); },
...
], function(err, results) {
if (err)
// handle error
else
res.send('tasks done'); // or whatever you want to send back
});
});
(depending on your tasks' signature, you could use async.apply instead of having to create a new function for each task)
Passing the response object around doesn't sound like a good idea, because – if I understand it correctly – your tasks don't have to generate a response themselves.