Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to return values from functions making HTTP request in node.js?

How to return values from functions making HTTP request in node.js?

Problem

The getStockValue() Function is called from another javascript file in the following way:

var r=require("./stockfile");
var returedData = r.getStockValue());

here returnedData contains only "-START-".

My objective is to get the body object returned from the function, after receiving the response. I've tried putting a return statement into the 'close' event handler, but it didn't work.

How should I do that?

function getStockValue() {

    var http = require('http');

    var options = {
        host: 'in.reuters.com',
        path: '/finance/stocks/overview?symbol=RIBA.BO',
        method: 'GET'

    };

    var body = "--START--";

    var req = http.request(options, function (res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));

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

        });

        res.on('close', function () {
            console.log("\n\nClose received!");
        });

    });

    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });
    req.end();

    return body + '... recieved';
}

exports.getStockValue = getStockValue;
Problem courtesy of: sbose

Solution

As this is an asynchronous operation if will return straight away and continue to run in the background, hense why you only receive -START-. You can resolve this with the help of a callback function. Heres how:

Call the function as follows:

r.getStockValue(function(result) {
     var returedData = result

     //... rest of your processing here
}));

and within the getStockValue function change to this:

function getStockValue(callback) {
   ...

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

   ...
}
Solution courtesy of: nav

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to return values from functions making HTTP request in node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×