Tuesday 23 May 2017

Node JS, how to use http.request POST into external var?

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 ?



via Yvo

No comments:

Post a Comment