我遇到了如何使用不同参数制作一系列函数的问题。我正在使用coffeescript和async,但我认为这是我对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调用的(总是数组中最后一个)三次。如何制作每个名称都有一个任务?
答案 0 :(得分:1)
尝试将for name in names
更改为names.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)
答案 1 :(得分:1)
实际上,在这种特殊情况下,您应该使用async的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
或许要记住一些事情。