如何从node.js中发出HTTP请求的函数返回值?

sbo*_*ose 1 javascript http node.js

getStockValue()函数以下列方式从另一个javascript文件调用:

var r=require("./stockfile");
var returedData = r.getStockValue());
Run Code Online (Sandbox Code Playgroud)

这里的returnData只包含"-START-".

我的目标是收到响应获取从函数返回的body对象.我已经尝试将一个return语句放入' close '事件处理程序中,但它没有用.

我该怎么办?

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;
Run Code Online (Sandbox Code Playgroud)

nav*_*nav 10

因为这是一个异步操作,如果直接返回并继续在后台运行,那么为什么你只收到它-START-.您可以借助回调函数解决此问题.这是如何做:

调用函数如下:

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

     //... rest of your processing here
}));
Run Code Online (Sandbox Code Playgroud)

并在getStockValue函数内改变为:

function getStockValue(callback) {
   ...

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

   ...
}
Run Code Online (Sandbox Code Playgroud)