语境:
我获取了一些“用户”。我想在返回响应之前了解更多关于这些特定用户的信息,因此我获取所有用户的详细信息并将其添加到结果中......然后在所有请求完成后返回结果。我在使用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