1

我在弄清楚如何制作具有不同参数的函数数组时遇到问题。我正在使用咖啡脚本和异步,但我认为这是我对 javascript 的理解的问题。

我想创建一个具有不同任务的函数数组。

names = ['Jeff', 'Maria', 'Steve']
tasks = []

for name in names
  tasks.push (callback)=>
      @controller.get_person name, (person) =>
        callback(null, person)

async.parallel(tasks, cb)

问题是该任务被 Steve(总是数组中最后一个)调用了 3 次。如何使每个名称都有一个任务?

4

2 回答 2

1

尝试更改for name in namesnames.forEach (name)=>. 注意后面的空间forEach

names = ['Jeff', 'Maria', 'Steve']
tasks = []

names.forEach (name)=>
  tasks.push (callback)=>
      @controller.get_person name, (person) =>
        callback(null, person)

async.parallel(tasks, cb)
于 2013-02-05T20:38:50.123 回答
1

实际上,在这种特殊情况下,您可能应该使用异步map

getPerson = (name, callback) =>
  @controller.get_person name, (person) ->
    callback(null, person)

async.map names, getPerson, (err, persons) ->
  // Do stuff with persons

请注意,如果您的@controller.get_person方法遵循将任何错误作为第一个参数传递给回调的节点实践,那么这就足够了:

async.map names, @controller.get_person, (err, persons) ->
  // Do stuff with persons

也许要记住一些事情。

于 2013-02-06T11:55:00.830 回答