0

新的节点程序员在这里,由于节点的异步性质,我很难理解如何从函数返回 http 请求的内容。这是我的程序的精简版。

//#1
function getwebsite(url) {
    var body;
    http.get(url, function (res) {
        res.on('data', function (chunk) {
            body += chunk;
            //***Right here, I need 'body' returned out of this function***
        });
    });
}


//#2
var a = getwebsite('website1.com');
var b = getwebsite('website2.com');

//#3
console.log(a+b);

我要做的就是 1:创建一个从站点获取数据的函数(如果重要,它的 JSON 和 XML),2:能够从我程序中的任何位置调用该函数,3:能够操作从我的函数中返回的任何数据。

你应该放置(和调用)回调函数的方式让我很头疼。我研究了几十个 http.get 和一般回调示例的示例,但还没有找到一个像我的示例中那样合并的示例。经过几天的失败尝试,我觉得如果有人可以在我的示例中展示如何做到这一点,它可能最终会在我的大脑中点击(手指交叉)。

4

2 回答 2

2

这是您要用于普通回调样式的基本模式:

function getwebsite(url, cb) {
    var body = "";
    http.get(url, function (res) {
        res.on('data', function (chunk) {
            body += chunk.toString();
            // you can't return a value from this function
            // the return value would be swallowed by the function
            // that is calling this function
            // which is not your code, but internal Node.js code
        });
        res.on("end", function() {
          cb(null, body)
        })
        res.on("error" function(error) {
          cb(error)
        })
    });
}

getwebsite("a", function(error, contentsA) {
  if (error) throw "Error getting website A."
  getwebsite("b", function(error, contentsB) {
    if (error) throw "Error getting website B."
    console.log(contentsA)
    console.log(contentsB)
  })
})

You may also want to look into flow-control libraries like Async (or my promise-based Faithful), or general-purpose promise libraries like RSVP.js. I recommend first getting accustomed with the basics of callbacks though.

For simple http requests, it's much easier to use the request module. You won't have to bind event listeners then. You just have a function that you can use in a similar way to the getwebsite function (which has issues!).

To get acquainted with async programming, you may want to try reading and writing some files with fs.readFile and fs.writeFile. For example, try to write contents of file A to file B. These are pretty simple functions, but you need to handle the callback-flow right. Node's http module is relatively complex in comparison. Or use the request module for that, as I mentioned.

于 2013-05-02T21:30:19.723 回答
0

您在数据有机会返回之前调用了 console.log() 。您可以将 body 变量带到更高的范围并附加到该范围内。IE

var body;

function getwebsite(url) {
    http.get(url, function (res) {

        res.on('data', function (chunk) {
            body += chunk;
            //***Right here, I need 'body' returned out of this function***
            outputBody(body);
        });
    });
}
var a = getwebsite('website1.com');
var b = getwebsite('website2.com');

function outputBody(val){
    console.log(val);
}
于 2013-03-30T06:33:17.337 回答