-1

Let's say I have code like:

app.get('/url', (req, res) => {
  if (req.some_magic == 1) {
    do_1();
  }
});

function do_1() {
  let requests = get_requests();
  setTimeout(function() { request({
    "uri": "url",
    "method": "POST",
    "json": rq
  }, (err, res, body) => {
    do_1();
  })}, 1000})
}

Basically for some requests that come to /url, I have to send bunch of requests to some service. How can I make this asynchronous so other requests from other people coming to /url wouldn't have to wait for do_1 to be finished? Or Node is already working like that? If yes, do you have any quick explanations or tutorials I could look into to understand how this works? I come from LEMP, so it's super different. Thanks a lot.

good_evening
  • 21,085
  • 65
  • 193
  • 298
  • See [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/1260204). This is essentially how almost all http APIs are built (using promises). The above http calls will be called asynchronously. You should *not* use `setTimeout` to check the result of any call. Use the native promise object instead. See the answer on the link for how to do that. – Igor Feb 05 '20 at 21:10
  • `Or Node is already working like that?` Node already works like that. between the time `request(...)` and `(err, res, body) => { do_1(); }` are invoked, the process is free to handle new incoming requests and run more asynchronous functions that process I/O in the background. – Patrick Roberts Feb 05 '20 at 21:10
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor Feb 05 '20 at 21:12

1 Answers1

3

Pretty much any function that involves getting data from outside of Node (such as a network request or file read) will use a function that is asynchronous. The documentation for the function should tell you (or at least imply it saying that the function returns a Promise or accepts a callback function as an argument).

The example you give shows the request module accepting a callback function.

The main exceptions are functions which are explicitly defined as being sync (such as fileWriteSync).

If you need to free up the main event loop explicitly, then you can use a worker thread. It's very rare that you will need to do this, and the main need comes when you are performing CPU intensive calculations in JS (which aren't farmed out to a library that is already asynchronous).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335