2

my node server needs to connect with other server in order to get some info and send it to the user. Since request is async in this situation I usually use addition libraries such as request-promise. But here I've got multiple calls from many points so I've created one function to handle them and this solution doesn't work.

apiCall1: function(req,res){
  var info = fetchFromOtherServer();
  console.log(info); // undefined
  res.send(info)
}
apiCall2: function(req,res){
  var info = fetchFromOtherServer();
  console.log(info); // undefined
  res.send(info)
}

function fetchFromOtherServer(){
  var options = {"method":"POST", "headers":{...},"uri":"{...}"}
  request(options, function(err,response,body){
   if(!err && response.statusCode == 200){
      console.log(body) // here is a body from other server
      return body;
    }
  }
}

So first I get an api call to function apiCall() which calls fetchFromOtherServer function. But before request is done node marks info variable as undefined and send it to the user. How can I change my code to tell node to wait until I get a response from that other server?

ampher911
  • 81
  • 1
  • 8

2 Answers2

0

You'll need a promise of your own, and you'll want to use then handlers on your promise. Take a look at promise documention and their examples.

apiCall1:

function(req,res){  var info_promise = fetchFromOtherServer();
  info_promise.then(function(info) {
    console.log(info); // undefined
    res.send(info)
  });
  # Also look into catch on promises for error
}

function fetchFromOtherServer(){
  return new promise(function(resolve, fail){
    var options = {"method":"POST", "headers":{...},"uri":"{...}"}
    request(options, function(err,response,body){
      if(!err && response.statusCode == 200){
        console.log(body) // here is a body from other server
        resolve( body);
      }
    }
  });
}
Sam Hartman
  • 6,210
  • 3
  • 23
  • 40
0

If you are using ES6 go with async await. It will simplify your code a great deal.

apiCall1: function(req,res){
  let response = await fetchFromOtherServer();
  // do something with response
}
apiCall2: function(req,res){
  let response = await fetchFromOtherServer();
  // do something with response
}

async function fetchFromOtherServer(){
  let options = {"method":"POST", "headers":{...},"uri":"{...}"}
  let response = await request(options);
  return response;
}
nilobarp
  • 3,806
  • 2
  • 29
  • 37
  • for now terminal sends me an error with "await" phrase. How can I include ES6 to my node project? Do something in package.json? – ampher911 Sep 25 '17 at 02:08
  • If you are not using `babel` or `typescript` then you need `node 7.x` for native `async` support. – nilobarp Sep 25 '17 at 02:11