使用async.parallel处理数组

我有两个单独的数组,我需要处理。 由于他们不是依赖,我想这样做asynchronous。

这是我的代码:

cats = ['snowball', 'berlioz', 'garfield', 'lucifer']; tigers = ['shere khan', 'hobbes', 'rajah']; async.parallel({ cats: async.apply(cats.forEach(function(item){ if(item == 'garfield') console.log('hide your lasagna'); else console.log('all safe'); })), tigers: async.apply(tigers.map(function(item){ if(item == 'hobbes') return 'eats tuna'; else return 'eats people'; })) }, function(error, results){ if(error) console.log(error); return; meals = JSON.parse(results['tigers']); console.log('tiger meals: '+meals); }); 

这是我得到的错误:

 TypeError: Cannot call method 'apply' of undefined 

怎么了?

另外,作为一个侧面的问题,我怎么能在这里实现async.forEachasync.map

您的代码段中有几个主要问题。

  • asynchronous处理asynchronousfunction。 asynchronous函数不能使用return关键字返回值,因为这是一个同步模式。 asynchronous函数必须将callback函数作为最后一个参数,并在完成时调用它。 你的匿名工作者function都不符合这个。
  • Array.forEach不返回任何东西,但是你正在使用它,就像它一样。 async.apply期望一个函数作为它的第一个参数。

开始一步一步:

编写一个命名的函数,它可以在一个参数上以asynchronous方式执行所需的操作

 function shouldWeHideTheLasagna(item, callback) { if (item === 'garfield') { process.nextTick(function () { callback(null, true); }); } else { process.nextTick(function () { callback(null, false); }); } } 

学习如何直接使用,而不是asynchronous。 然后结合使用async.map, async.map(cats, shouldWeHideTheLasagna, function (error, results) {}); 然后重复老虎一个,希望现在有足够的灯泡,你会准备尝试async.parallel和sub-asyncs的组合。 但是这是一件棘手的事情,所以慢慢来一步一步了解每一步的工作原理。

我认为你误解了async是用来做什么的。 asynchronous是用于已经是asynchronous的function,并为您的callback提供组织。 例如,如果您需要依次调用三个IO事件,则可以使用Async.series来确保每个事件都在之前运行,而不必担心callback地狱

在你的场景中,所有的函数都是同步的,因此asynchronous不会真的改善你的运行时间。 相反,我会推荐使用Array.map和Array.forEach等核心数组原型。