我正在使用 NodeJS 设置一个抓取器,我很难找到使用 async.parallel 时传递数据的正确方法。
这是批处理函数,它接收 zip_results 对象内的数组中的邮政编码列表。我正在尝试将数组 asyncTasks 设置为由异步运行的函数数组。我想为每个邮政编码调用的函数是 Scraper.batchOne,我想向它传递一个邮政编码和工作版本。现在,该函数被立即调用。我尝试将对 Scraper.batchOne
的调用包装在一个匿名函数中,但这失去了索引变量 i
的范围并且总是以未定义的值发送。
如何才能使函数连同一些参数一起传递给数组?
// zip_results: {job_version: int, zip_codes: []}
Scraper.batch = function (zip_results) {
//tasks - An array or object containing functions to run, each function
//is passed a callback(err, result) it must call on completion with an
//error err (which can be null) and an optional result value.
var asyncTasks = [], job_version = zip_results.job_version;
for (var i=0; i < zip_results['zip_codes'].length; i++) {
asyncTasks.push(Scraper.batchOne(zip_results['zip_codes'][i], job_version));
}
// Call async to run these tasks in parallel, with a max of 2 at a time
async.parallelLimit(asyncTasks, 2, function(err, data) { console.log(data); });
};
最佳答案
为什么不改用 async.eachLimit? (使用 async.parallel 你需要使用 bind/apply 技术)
async.eachLimit(zip_results['zip_codes'], 2, function(zip, next) {
Scraper.batchOne(zip, zip_results.job_version));
return next();
}, function(err) {
// executed when all zips are done
});
关于javascript - NodeJS Async - 将参数传递给回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28617990/