【问题标题】:NodeJS Async - Pass parameters to callbackNodeJS 异步 - 将参数传递给回调
【发布时间】:2015-02-20 14:08:10
【问题描述】:

我正在使用 NodeJS 设置一个抓取工具,但在使用 async.parallel 时,我很难找出传递数据的正确方法。

这是批处理函数,它接收 zip_results 对象内部数组中的邮政编码列表。我正在尝试将数组 asyncTasks 设置为要由 async 运行的函数数组。我想为每个邮政编码调用的函数是 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); });

};

【问题讨论】:

    标签: javascript node.js callback asynccallback


    【解决方案1】:

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

    【讨论】:

    • 看起来这开始很好,但是在处理了前两个结果之后,进程就挂了
    • 我编辑了解决方案,当然我们需要在完成项目后调用回调(上例中的next())。如果您的批处理正在异步工作,您需要将 next 作为参数传递给 batchOne 函数并在完成后调用它。
    【解决方案2】:

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

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

    希望这会有所帮助。

    【讨论】:

    • 但这不会在加载时立即执行吗?在这种情况下,Scraper.batch 已经是对其他内容的回调。
    • 设置作用域的外部函数会被调用onload...内部函数只会在'parallelLimit'被调用时被调用。
    • 啊,笨蛋,你说得对。现在我的问题是,当我调用async.parallelLimit(tasks, number_of_runs) 时,它会在我得到number_of_runs 迭代后立即停止。任何线索为什么会发生这种情况?
    猜你喜欢
    • 2014-04-20
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    相关资源
    最近更新 更多