Ajay Gaur
Ajay Gaur

Reputation: 5270

Node.js and axios : How to return response after asynchronous request to another server?

I'm new to node.js and from the postman I'm making a post call to my node server which further makes a call to remote server. I'm using axios to make the call, the api is return something like this :

exports.fetchFromRemoteServer = function(req, res, next){
  const query = req.query;

  axios({
        method: 'post',
        url: 'http://www.someUrl.com',
        params: query
      }).then(function(response){
        console.log(response);
        res.send('data', response);
      }).catch(err => console.log(err));
}

Whenever I'm making this call, I get the data on the node server but I don't know how to make that async so that whenever it comes in the .then of the api call res.send start working. The postman keep showing me the loading state.

Upvotes: 1

Views: 2072

Answers (1)

Ajay Gaur
Ajay Gaur

Reputation: 5270

I found solution to this using the async module and the solution looked like :

exports.fetchFromRemoteServer = function(req, res, next){
  const query = req.query;

async.parallel([
 function(callback){
   axios({
      method: 'post',
      url: 'http://www.someUrl.com',
      params: query
    }).then(function(response){
      callback(false, response);
    });
}],function(error, result){
   res.json(result[0].data.results);
 }); 
}

Upvotes: 2

Related Questions