简体   繁体   English

将参数传递给async.js任务

[英]Pass parameter to async.js task

I have to iterate through a given JSON object and create a task for each object in there. 我必须遍历给定的JSON对象,并为其中的每个对象创建一个任务。 The given tasks require information from this JSON object as well and I wonder how I can pass these information to my task so that it is available when executed. 给定的任务也需要来自此JSON对象的信息,我想知道如何将这些信息传递给任务,以便在执行时可以使用。

Building my task array: 构建我的任务数组:

var asyncScrapeTasks = [];
var resources = JSON.parse(body);
for(var i=0; i<resources.items.length; i++)
{
    asyncScrapeTasks.push(function (callback)
    {
        console.log(resources.items[i].id);
    });
}

Executing my tasks: 执行我的任务:

async.parallelLimit(asyncScrapeTasks, 5, function() {
    callback(null, "Done");
});

My problem: 我的问题:

Right now console.log(resources.items[i].id); 现在console.log(resources.items[i].id); returns undefined, which makes sense for me, because the index i is not known at the time the functions being executed, but I wonder how I can solve my problem. 返回undefined,这对我来说很有意义,因为在执行函数时尚不知道索引i,但是我想知道如何解决我的问题。

As I don't have enough reputation to add comment, I am writing as answer. 由于我没有足够的声誉来添加评论,因此我正在写答案。 Sorry. 抱歉。

Is there any specific reason to use paralleLimit? 使用paralleLimit是否有任何特定原因? async.js have each which could iterate collection and perform operation on each item. 每个async.js都可以迭代收集并在每个项目上执行操作。 This function applies the function iteratee to each item in collection, in parallel. 此函数并行地将函数iteratee应用于集合中的每个项目。 async.js each 每个async.js

If you want to limit the operations: async.js eachLimit 如果要限制操作: async.js eachLimit

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

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