Andre M
Andre M

Reputation: 7536

Ensuring nodejs server does not respond before async call?

I have a NodeJS server that receives a request from a client and then makes a request itself to an upstream rest service. The issue I am having is that my call to the upstream rest service, via express, is asynchronous, so the calling function is returning to the client, before it has received the response from the upstream server.

client --->  serverA ---> serverB

Example:

app.all('/api/*', function(req,res) {
   request(...)
   // wait for response from request somehow
})

Everywhere I look I am told not to make synchronous calls in NodeJS, because it won't scale, but at this point I don't event have something that will behave as expected.

Can anyone suggest the right way to solve this issue?

Upvotes: 0

Views: 463

Answers (3)

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 363

To achieve this,no need to write synchronous code

app.all('/api/*', function(req,res) {
 request({url : .. , timeout : ..},function(err, resp, body){
  //error handling
   res.send("your response");
});


})

Upvotes: 0

Nitish Agarwal
Nitish Agarwal

Reputation: 700

You have to pass a callback function to your upstream service.

app.all('/api/*', function(req,res) {
   request(function(err, response){
     if(err){
       res.jsonp({'status':200,'message':'ALL OK'});
     } else {
       res.jsonp({'status':201,'message':'Something went wrong'});
     }
   });
})

you can refer to this https://www.npmjs.com/package/request

Upvotes: 0

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

your express routes doesn't response automatically. If you doesn't set response then server wont response (some time later you will get error).

For example

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

});

and if you send request to this router it won't respond. Therefore you don't have to worry.

And strictly to your problem. Your server request have to do something after finish its call (callback or promise).

app.all('/api/*', function(req,res) {
   request(function(response){
       //callback
       //here you send response
       res.send('OK');
   });
})

but what if your server request fails? Maybe your server request also return error?

app.all('/api/*', function(req,res) {
   request(function(err, response){
     if(err){
       res.send('ERROR');
     } else {
       res.send('OK');
     }
   });
})

I can't be more specific because I don't know details. But my answer may help you a little.

Upvotes: 2

Related Questions