Tuesday, 18 April 2017

Node server async call to backend service

I am new to Node and I am writing my very first node server. It should answer to a simple get request with a simple page after calling a backend rest service.

I am using express to manage the request and the axios package to make the backend request. The problem is that the server is blocking the event loop and I have problems understanding how to make the call to the backend asynchronous.

As of now the frontend server can only manage one request at a time!! I expected that if the backend service takes 10 seconds to answer everytime, the frontend server can answer two concurrent request in 10 seconds and not in 20 seconds.

Where am I wrong?

Here is an extract of the frontend node code:

app.get('/', function(req, res) {

      //Making the call to the backend service. This should be asynchronous...
      axios.post(env.get("BACKEND_SERVICE"), 
      { "user": "some kind of input"})
        .then(function(response){

        //do somenthing with the data returned from the backend...

        res.render('homepage');
        })
    }

And here it is and extract of the backend node code:

app.post('/api/getTypes', jsonParser, function (req, res) {

      console.log("> API request for 'api/getTypes' SLEEP");
      var now = new Date().getTime();
      while(new Date().getTime() < now + 10000){ /* do nothing */ }
      console.log("> API request for 'api/getTypes' WAKE-UP");

      res.json({"types":"1"});
    }


via Roberto

No comments:

Post a Comment