-3

In our project, we make a call to a REST web service with Node using HTTP request. We can see the result when we log it into the console. But we would like to store it or use it outside of the HTTP request. How can we achieve that?

var http = require('http');

var options = {
  host: 'http:\\example.com',
  port: 80,
  path : '/site/status?tag=A7351&date=09JAN&name=LASTNAME',
  method : 'GET'
};

var result;

http.request(options, function(res){
  var body = '';

  res.on('data', function (chunk) {
    body += chunk;
  });
  res.on('end', function () {
    result = JSON.parse(body);
    console.log(result, "INSIDE"); //Shows the JSON result
  });
}).end();

console.log(result, "OUTSIDE"); //Shows Undefined

The result is in this format:

{
  error: 0,
  statut: 'STATUTTTTT',
  origine: 'PLACEEE',
  destination: 'PARIS',
  onwardDate: null
}

We need to be able to get the result outside of the HTTP call.

hong4rc
  • 3,999
  • 4
  • 21
  • 40
  • 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) – jonrsharpe Jan 13 '19 at 09:16
  • Thank you for your response @jonrsharpe. As a newbie didn't know how to use the asynchronous call. can you please guide me through it. this is my first ever project in dev... – Hamza Baydara Jan 13 '19 at 10:07

1 Answers1

0

The issue is that you're making an asynchronous call, but not handling it correctly. Dialogflow's library requires that when you make an async call you return a Promise.

The easiest solution is for you to switch from using the request library to using the request-promise-native library and to return the Promise.

See other answers on Stack Overflow for examples and more information.

Prisoner
  • 49,922
  • 7
  • 53
  • 105