Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js wait for response

Tags:

node.js

I have a very limited knowledge about node and nob-blocking IO so forgive me if my question is too naive.

In order to return needed information in response body, I need to

  • Make a call to 3rd party API
  • Wait for response
  • Add some modifications and return JSON response with the information I got from API.

My question is.. how can I wait for response? Or is it possible to send the information to the client only when I received response from API (as far as I know, connection should be bidirectional in this case which means I won't be able to do so using HTTP).

And yet another question. If one request waits for response from API, does this mean than other users will be forced to wait too (since node is single-threaded) until I increase numbers of threads/processes from 1 to N?

like image 309
evfwcqcg Avatar asked Jan 16 '13 14:01

evfwcqcg


2 Answers

You pass a callback to the function which calls the service. If the service is a database, for example:

db.connect(host, callback);

And somewhere else in the code:

var callback = function(err, dbObject) {
    // The connection was made, it's safe to handle the code here
    console.log(dbObject.status);
    res.json(jsonObject, 200)
};

Or you can use anonymous functions, so:

db.connect(host, function(err, dbObject) {
    // The connection was made, it's safe to handle the code here
    console.log(dbObject.status);
    res.json(jsonObject, 200)
});

Between the call and the callback, node handles other clients / connections freely, "non-blocking".

like image 130
randunel Avatar answered Nov 16 '22 19:11

randunel


This type of situation is exactly what node was designed to solve. Once you receive the request from your client, you can make a http request, which should take a callback parameter. This will call your callback function when the request is done, but node can do other work (including serving other clients) while you are waiting for the response. Once the request is done, you can have your code return the response to the client that is still waiting.

The amount of memory and CPU used by the node process will increase as additional clients connect to it, but only one process is needed to handle many simultaneous clients.

Node focuses on doing slow I/O asynchronously, so that the application code can start a task, and then have code start executing again after the I/O has completed.

like image 45
JeffS Avatar answered Nov 16 '22 21:11

JeffS