node.js - 使用 async.parallel 处理数组

标签 node.js 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

最佳答案

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

  • 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/

相关文章:

node.js - npm 错误! EPROTO : protocol error, 符号链接(symbolic link) '../@babel/parser/bin/babel-parser.js' -> '/home/vagrant/code/proadco.test/node_modules/.bin/parser'

node.js - 在 async.each 中检索异步回调信息的简单方法

swift - 解析嵌套的完成处理程序

perl - 使用 Mojolicious 的异步聊天服务器

node.js - Bower 初始化命令错误

windows - 如何在 Windows 中使用某些预定义端口从 cmd 运行 node.js 应用程序

java - 运行平均种子时 jasmine_node 失败

javascript - 具有复杂计算的异步回调Javascript

c# - AsyncPostBackTrigger Gridview 分页

multithreading - 在进行异步I/O时,内核如何判断I/O操作是否完成?