1

Sorry if this is a basic question. I'm just starting my 3rd week of doing Node.js programming! I looked around and didn't see an answer to this, specifically. Maybe it's just assumed when answering questions about child_process.spawn/fork by those who know this stuff better than I do.

I have a Node/Express app where I want to take in an HTTP request, save a bit of data to Mongo, return success/error, but...at the same time kick off a process to take some of the data and do a lookup against a web API. I want to save that data back to Mongo, but there's no need to have that communicated back to the HTTP client. (I'll probably log the success/error of that call somewhere.)

How do I kick off that 2nd task to run independent of the main request and not cause the response to wait for it to complete?

The 2nd task will also be written in Node.js. I'd like it to just be another function in the same file, if possible.

Thanks in advance!

Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
  • 1
    Send the response to the request, then continue processing the rest of it. You don't have to wait till you're done doing the rest of the work to send a response to the request. – Kevin B Oct 13 '15 at 21:38
  • It's really that simple? I'll give it a go. Thanks! – Andrew Hedges Oct 13 '15 at 21:38
  • 1
    To be absolutely sure, you can move it to another callstack with `process.nextTick(function () {/* rest of code here */})`, that way the synchronous logic won't delay it either. – Kevin B Oct 13 '15 at 21:39
  • 1
    relevant: http://stackoverflow.com/q/16180502/201952 – josh3736 Oct 13 '15 at 21:50

1 Answers1

2

I don't see why you would need spawning another process just for that. In node you are not limited to the http request lifecycle to run stuff like other frameworks. This should do it:

function yourHandler(req, res, next) {
      dataAccess.writeToMongo(someData, function(err, res) {
           var status = err ? 500 : 200;
           // write back to response already!
           res.status(status);
           res.end();

           // do not completely terminate yet
           // kick off web api call 
           apiClient.doSomething();
      });
}
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44