0

I am trying to return the result of a HTTP.request result outside the request.

Here is my code :

function repromptFunction() {
    var http = require('http');

    var options = {
        host: 'api.domain.com',
        port: 80,
        path: '/path/file.json',
        method: 'POST'
    };

    http.request(options, function(res) {
        res.setEncoding('utf8');
        var data = '';
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function() {
            var recv = JSON.parse(data);
            var repromptText = recv.forecast.txt_forecast.forecastday[0].fcttext_metric;
            return repromptText;
        });
    }).end();
}

console.log('final value is ' + repromptFunction());

But each time, the console.log return undefined. I understand that the code is executed in an asynchronous way.

What should I do to be sure to receive anything but not this undefined result to my Console.log ?

Yvo
  • 53
  • 3

1 Answers1

0

Your return repromptText is returning from the anonymous function that was passed to http.request. The repromptText() function doesn't return anything here. You would need to put your console.log into the end callback and/or have that callback trigger the work you wish to do.

bsechrist
  • 21
  • 4