如果您想在没有任何类型的库(如异步)的情况下执行此操作,那么您必须编写自己的计数器来跟踪所有异步响应何时完成:
var request = require('request');
function loadAll(list, fn) {
var cnt = list.length;
var responses = [];
list.forEach(function(url, index) {
request(url, function(error, response, body) {
if (error) {
fn(error);
} else {
responses[index] = response;
--cnt;
if (cnt === 0) {
fn(0, responses);
}
}
});
})
}
loadAll(['http://www.yahoo.com', 'http://www.gmail.com'], function(err, results) {
if (!err) {
// process results array here
}
});
如果您要在 node.js 中执行许多异步操作,那么获得像 Bluebird 这样的 Promise 库将为您节省大量时间。例如,我认为您可以通过以下方式执行上述操作(未经测试):
var Promise = require("bluebird");
var requestP = Promise.promisfy(require("request"));
Promise.map(['http://www.yahoo.com', 'http://www.gmail.com'], requestP).then(function(results) {
// process the array of results here
});