NodeJS Async - 将参数传递给回调
NodeJS Async - Pass parameters to callback
我正在使用 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 你需要使用绑定/应用技术)
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
});
你可以做一个自调用的匿名函数,并在调用方法后传递你想保留的参数,如下所示:
(function(asyncTasksArr, index, zipResults, jobVersion){
return function(){
asyncTasksArr.push(Scraper.batchOne(zipResults['zip_codes'][index], jobVersion));
}
}(asyncTasks, i, zip_results, job_version));
希望对您有所帮助。
我正在使用 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 你需要使用绑定/应用技术)
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
});
你可以做一个自调用的匿名函数,并在调用方法后传递你想保留的参数,如下所示:
(function(asyncTasksArr, index, zipResults, jobVersion){
return function(){
asyncTasksArr.push(Scraper.batchOne(zipResults['zip_codes'][index], jobVersion));
}
}(asyncTasks, i, zip_results, job_version));
希望对您有所帮助。