简体   繁体   English

NodeJS异步-将参数传递给回调

[英]NodeJS Async - Pass parameters to callback

I'm setting up a scraper using NodeJS, and I'm having a hard time figuring out the right way to pass data around when using async.parallel. 我正在使用NodeJS设置刮板,并且在使用async.parallel时很难确定正确的数据传递方式。

Here's the batch function, which receives the list of zip codes in an array inside of the zip_results object. 这是批处理功能,它在zip_results对象内部的数组中接收邮政编码列表。 I'm trying to setup the array asyncTasks as an array of functions to be run by async. 我正在尝试将数组asyncTasks设置为要由异步运行的函数数组。 The function I want called for each zip code is Scraper.batchOne, and I want to pass it a zip code and the job version. 我想为每个邮政编码调用的函数是Scraper.batchOne,我想向其传递一个邮政编码和作业版本。 Right now, the function is called immediately. 现在,该函数立即被调用。 I tried wrapping the call to Scraper.batchOne in an anonymous function, but that lost the scope of the index variable i and always sent in undefined values. 我尝试Scraper.batchOne的调用包装在一个匿名函数中,但这丢失了索引变量i的范围,并且始终以未定义的值发送。

How can make it so that the function is passed to the array, along with some parameters? 如何使函数与一些参数一起传递到数组?

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

};

Why don't you use async.eachLimit instead? 为什么不改用async.eachLimit? (With async.parallel you would need to use bind / apply techniques) (使用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
});

You can do a self invoking anonymous function and pass the parameters that you want to retain after the method is called like this: 您可以执行自调用匿名函数,并在调用该方法后传递要保留的参数,如下所示:

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM