nodejs循环中的多个http请求 [英] nodejs multiple http requests in loop

查看:1815
本文介绍了nodejs循环中的多个http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在节点中创建简单的feed阅读器,而我在node.js中遇到了多个请求的问题。
例如,我得到的网址类似于:

I'm trying to make simple feed reader in node and I'm facing a problem with multiple requests in node.js. For example, I got table with urls something like:

urls = [
"http://url1.com/rss.xml",
"http://url2.com",
"http://url3.com"];

现在我想获取每个网址的内容。第一个想法是使用 for(var i in urls),但这不是个好主意。最好的选择是异步做,但我不知道怎么做。

Now I want to get contents of each url. First idea was to use for(var i in urls) but it's not good idea. the best option would be to do it asynchronously but I don't know how to make it.

任何想法?

编辑:

我收到了这段代码:

var data = [];
for(var i = 0; i<urls.length; i++){
    http.get(urls[i], function(response){
    console.log('Reponse: ', response.statusCode, ' from url: ', urls[i]);
    var body = '';
    response.on('data', function(chunk){
        body += chunk;
    });

    response.on('end', function() {
        data.push(body);
    });
}).on('error', function(e){
    console.log('Error: ', e.message);
});
}

问题是第一个是调用线http.get ...循环中的每个元素以及在该事件之后响应.on('data')被调用并且在该response.on('end')之后。它搞得一团糟,我不知道如何处理这个问题。

Problem is that first is call line "http.get..." for each element in loop and after that event response.on('data') is called and after that response.on('end'). It makes mess and I don't know how to handle this.

推荐答案

默认节点 http 请求是异步的。您可以在代码中按顺序启动它们,并调用一个在所有请求完成后启动的函数。您可以手动执行(计算已完成的vs已启动的请求)或使用async.js

By default node http requests are asynchronous. You can start them sequentially in your code and call a function that'll start when all requests are done. You can either do it by hand (count the finished vs started request) or use async.js

这是无依赖方式(忽略错误检查):

This is the no-dependency way (error checking omitted):

var http = require('http');    
var urls = ["http://www.google.com", "http://www.example.com"];
var responses = [];
var completed_requests = 0;

for (i in urls) {
    http.get(urls[i], function(res) {
        responses.push(res);
        completed_requests++;
        if (completed_requests == urls.length) {
            // All download done, process responses array
            console.log(responses);
        }
    });
}

这篇关于nodejs循环中的多个http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆