0

A simple question. I am trying to update a variable inside a function passed to another function. Of course, it will not work like this, but what is the workaround for responseText to be updated inside http.request

var responseText;
var req = http.request(options, function(res) {
  var status = res.statusCode;

  if (status == 400) {
    responseText = "failed";
  } else if (status == 200) {
    responseText = "success";
  }
});
req.write(post_data);
req.end();

console.log(responseText)

What are the solutions to resolve this.? Thanks

Sammy
  • 13
  • 3
  • 3
    but it works, your problem is that console.log is invoked before anything is set to responseText – Maciej Kozieja Dec 13 '17 at 16:56
  • 1
    see this https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – vibhor1997a Dec 13 '17 at 16:58
  • you can also use [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) and [promise](https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Promise) – Maciej Kozieja Dec 13 '17 at 16:59

0 Answers0