上下文:
我找了一些“用户”。我想在返回响应之前了解有关这些特定用户的更多信息,因此我获取所有用户的详细信息并将其添加到结果中...然后在所有请求完成后返回结果。我在使用parallel
电话时遇到了问题:
async = require 'async'
# Assume I don't know how many users are here. Test data.
users = [
name: 'user1'
,
name: 'user2'
]
# Fake add some extra data to the user.
fetchUser = (name, cb) ->
setTimeout (->
user =
name: name
email: name + '@email.com'
cb user
), 1 * 1000
fetchUsers: (userList, cb) ->
result =
count: userList.length
users: []
# runInParallel = []
# for user in userList
# fetchUsers(user.name) # Yea, not going to work either.
#
# async.parallel runInParallel
async.parallel [
fetchUser('user1') # Yea, how do I build an array of a function?
fetchUser('user2')
], (err, user) ->
#console.log 'returned user ' + user.name # If this calls back once, then this won't work....
if !err
result.users.push user
cb result
# Do it.
fetchUsers users, (result) ->
console.log result
答案 0 :(得分:2)
你可以简单地做一张地图。 我用原生的js写它,但是你得到了它。
var usersFetchFunctions = users.map(function (user) {
return function () { ... }
});
async.parallel(usersFetchFunctions, function (err) { ... });
答案 1 :(得分:2)
请勿使用async.parallel,请使用async.each http://caolan.github.io/async/docs.html#each
async.each userList, fetchUser, (err, users) ->