我有两个单独的数组需要处理。由于它们不相互依赖,我想异步执行此操作。
这是我的代码:
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.forEach
和 async.map
?
最佳答案
您的代码片段中有几个主要问题。
- async 处理异步函数。异步函数不能使用 return 关键字返回值,因为这是同步模式。异步函数必须将回调函数作为最后一个参数,并在完成时调用它。您的两个匿名工作函数都不符合此要求。
- Array.forEach 不会返回任何内容,但您可以像返回一样使用它。 async.apply 期望一个函数作为其第一个参数。
一步一步开始:
编写一个命名函数,以异步方式对单个参数执行您想要的操作
function shouldWeHideTheLasagna(item, callback) {
if (item === 'garfield') {
process.nextTick(function () {
callback(null, true);
});
} else {
process.nextTick(function () {
callback(null, false);
});
}
}
了解如何直接使用它而不使用异步。然后练习将其与 async.map、async.map(cats, shouldWeHideTheLasagna, function (error, results) {});
结合使用,然后对老虎重复一次,希望现在有足够的灯泡亮起,您将准备好尝试 async.parallel 与子异步的组合。但这是一件棘手的事情,所以慢慢地一步一步来,了解每一步是如何工作的。
关于node.js - 使用 async.parallel 处理数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252709/