您已经发现,
async.parallel()只能并行化本身是异步的操作。如果操作是同步的,则由于node.js具有单线程特性,因此这些操作将一个接一个地运行,而不是并行运行。但是,如果操作本身是异步的,则
async.parallel()(或其他异步方法)将立即启动所有操作并为您协调结果。
这是使用的一般思路
async.map()。我
async.map()之所以使用它,是因为这样的想法是,它将一个数组作为输入并以与原始数组相同的顺序生成一个结果数组,但是并行运行所有请求,这似乎与您想要的内容一致:
var async = require("async");var request = require("request");// create list of URLsvar lookup_list = [];for (var i = 0; i < 20; i++) { var index = Math.round(Math.random() * 495) + 1; var url = 'http://localhost:3001/generate?file=' + index; lookup_list.push(url);}async.map(lookup_list, function(url, callback) { // iterator function request(url, function (error, response, body) { if (!error && response.statusCode == 200) { var body = JSON.parse(body); // do any further processing of the data here callback(null, body); } else { callback(error || response.statusCode); } });}, function(err, results) { // completion function if (!err) { // process all results in the array here console.log(results); for (var i = 0; i < results.length; i++) { // do something with results[i] } } else { // handle error here }});而且,这是一个使用Bluebird Promise的版本,并且有点类似地
Promise.map()用于迭代初始数组:
var Promise = require("bluebird");var request = Promise.promisifyAll(require("request"), {multiArgs: true});// create list of URLsvar lookup_list = [];for (var i = 0; i < 20; i++) { var index = Math.round(Math.random() * 495) + 1; var url = 'http://localhost:3001/generate?file=' + index; lookup_list.push(url);}Promise.map(lookup_list, function(url) { return request.getAsync(url).spread(function(response, body) { if response.statusCode !== 200) { throw response.statusCode; } return JSON.parse(body); });}).then(function(results) { console.log(results); for (var i = 0; i < results.length; i++) { // process results[i] here }}, function(err) { // process error here});


