0

I am performing a "GET" request to a url to get back a response, so i have a function that handles the request

var makeRequest = function(objs, callback){
    var url = 'adasda..';
    //...
    var result = null;
    request(url, function(error, response, body){
          if(!error && response.statusCode === 200){
                result = body;
                callback(null, body)
          }
    });

   return result;
}

In my main function i am invoking the above function

function main(values, callback){
  //...some logic
   var newValue={....}

   if(some conditional){
       newValue = makeRequest(values,callback); //newValue gets appended with new data
   }

   sendData(null, newValue, callback); //this function does a post 
}

var sendData = function(....){}

I noticed once makeRequest gets executed, it immediately goes ahead and then executes sendData and thats because the request module is an asynchronous operation.

How can i wait till the newValue object gets populated and then sendData() should be invoked?

RRP
  • 2,563
  • 6
  • 29
  • 52
  • You can't wait. You must use the response in the callback and any code that you want to be executed after the response is received must actually be in the callback. This is how you program with asynchronous responses. It is different than synchronous programming. Many examples provided in the duplicate. – jfriend00 Jan 22 '16 at 01:19

1 Answers1

0

Wait until the callback fires. I've updated your code.

var makeRequest = function(objs, callback) {
  var url = 'adasda..';

  request(url, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      callback(null, body)
    }
  });
};

function main(values, callback) {

  var newValue = {}

  if (some conditional) {
    makeRequest(values, function(error, result) {
      // Call sendData once we get the data
      sendData(null, result, callback);
      callback(error, result);
    }); 
  }

}

var sendData = function() {};

To avoid nested callbacks you can use Promises.

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64