Search code examples
node.jsnode-request

Node js POST request not working if called inside GET request callback


I make get request to get JSON data form one API and inside the callback of the get request I make another POST call to POST this data to another API. This doesn't seem to work me.

var request = require('request');

function startFetchingHistory(postToApp){
request.get(url, function(err, res, body) {
   postToApp(body);
});
}



function postToApp(body) {

 var options = {
uri: 'http://localhost:3079/history',
method: 'POST',
json : body
};

request(options, function(error, response, body) {
console.log(error+response+body);
if (!error && response.statusCode == 200) {
  console.log(body);
} else {
  logger.error('Error from server is' + error);
    }
  });
}

Above doesn't work. By "doesn't work", I mean that POST request callback is never called. However If I call postToApp() method directly, POST request goes though successfully.


Solution

  • Two important concepts

    1. request is async in nature
    2. API called will return when you return from the main handler

    If you look at your function postToApp, when you call

    request(options, function(error, response, body) {

    This goes to your eventloop and the function executes and completes without ever waiting for the post call to complete.

    Now, what you want to do it wait for the function postToApp to complete. The easiest and IMO, the right way to do this if to respond to your API inside the callback of postToApp

    var request = require('request');
    
    function startFetchingHistory(postToApp) {
      request.get(url, function (err, res, body) {
        postToApp(body, (postResponse) => {
          //respond back with the result/error to your API
        });
      });
    }
    
    
    
    function postToApp(body, callback) {
      var options = {
        uri: 'http://localhost:3079/history',
        method: 'POST',
        json: body
      };
      request(options, function (error, response, body) {
        console.log(error + response + body);
        if (!error && response.statusCode == 200) {
          console.log(body);
          callback(body) // call the function back with the data you want to process;
        } else {
          logger.error('Error from server is' + error);
          callback(error) // call the function back with error to process;
        }
      });
    }