0

I need to make two http-requests, which I would like to have in two seperated functions. I thought synchronously:

.. make the first http-request and return the response

.. pass the response to the second function which makes the second http-request

here the first function:

function getObjTypes(cfg) {

  // request-options
  var post_options = {
    host: cfg.apiHost,
    port: cfg.apiPort
  };

  // request
  var ObjectTypes = [];

  var post_req = http.request(post_options, function(res) {

    res.setEncoding('utf8');
    let resBody = '';

    res.on('data', function (chunk) {
      resBody += chunk;
    });

    res.on("end", () => {
      var resObject = JSON.parse(resBody);    

      return ObjectTypes; // Here the ObjectTyes needs to be passed as a return

    });
  });
  post_req.end(); 
}

I know whats is wrong.. the http-request is async, so the second function is called before the response fron the first function is there.. but how would I "fix" this?

Arschibald
  • 127
  • 2
  • 10
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – yeya Nov 12 '18 at 13:30
  • Is there a specific reason you need to use `http-request`? You may want to look at a library like [`axios`](https://www.npmjs.com/package/axios) that returns Promises and then look into [`async/await`](https://javascript.info/async-await) to see how you can write synchronous-style code while working with requests – dpopp07 Nov 12 '18 at 13:43

0 Answers0