发出未知数量的异步GET请求的最佳解决方案是什么?
例如,您有以下 url "http://www.example.org/",并且您希望向以下路径发出一组异步请求:
[
'http://www.example.org/A-1.html',
'http://www.example.org/A-2.html',
'http://www.example.org/A-3.html',
'...',
'http://www.example.org/B-1.html'
'http://www.example.org/B-2.html'
'...'
]
等等。如果,说,"...C-12.html' 不存在,您得到无效的响应标头代码。您将如何发出一组并行请求?
var request=require('request');
var vrlList = [
'http://www.example.org/A-1.html',
'http://www.example.org/A-2.html',
'http://www.example.org/A-3.html',
'...',
'http://www.example.org/B-1.html'
'http://www.example.org/B-2.html'
'...'
];
var outPutData = [];
forEach(function(url,index){
request({ method: 'GET', uri: url }, function (error, response, body) {
outPutData.push({"url":url,data:body});
}).on('data', function(data) {
}).on('error', function(err) {
console.log(err)
}).on('response', function(response) {
response.on('data', function(data) {
})
})
});
我认为这是一项算法任务。
假设您有 A-Z(要处理的 26 行)。您也可以并行实现仅 15 个线程。
因此,您将process
数组中的前 15 行加载:A-O
;然后,在process
上启动多线程进程。例如,当B-56
未定义(未定义)时,您只需抛出异常并在process
数组中加载下一行P
同时排除第 B
行。
这样,您将循环访问所有剩余的行P-Z
.
这是我使用 JQuery 延迟对象想出的东西。
function getUrls(urls, callback) {
var result,
i = 0;
var g = $.Deferred()
.done(callback);
urls.forEach(function(u, i) {
$.getJSON(u, function(data) {
// Do whatever processing you need to do here
if (++i === dcnames.length) {
g.resolve(result) // invoke the callback with the result
}
})
})
}
延迟对象等待解析,直到进行最后一次调用。尽管 forEach 是一个同步(阻塞)进程,但由于 getJSON 本身是异步的,因此循环将并行运行所有请求,并等待解析,直到它们全部完成。