NodeJSasynchronous – 传递参数给callback

我正在使用NodeJS设置一个刮板,我很难找出使用async.parallel传递数据的正确方法。

这里是批处理函数,它接收zip_results对象内的数组中的邮政编码列表。 我正在尝试将数组asyncTasks设置为由async运行的函数数组。 我想为每个邮政编码调用的函数是Scraper.batchOne,我想通过它一个邮政编码和工作版本。 现在,函数立即被调用。 我试图在一个匿名函数中包装调用Scraper.batchOne ,但是失去了索引variablesi的范围,并且总是以未定义的值发送。

怎样才能使函数传递给数组,以及一些参数?

 // 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); }); }; 

您可以执行一个自调用匿名函数,并在调用方法之后传递要保留的参数,如下所示:

 (function(asyncTasksArr, index, zipResults, jobVersion){ return function(){ asyncTasksArr.push(Scraper.batchOne(zipResults['zip_codes'][index], jobVersion)); } }(asyncTasks, i, zip_results, job_version)); 

希望这可以帮助。

为什么不使用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 });