0

语境:

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

2 回答 2

2

你可以简单地做一张地图。我用本机 js 编写它,但你明白了。

var usersFetchFunctions = users.map(function (user) {
  return function () { ... }
});

async.parallel(usersFetchFunctions, function (err) { ... });
于 2013-04-15T21:33:18.300 回答
2

不要使用 async.parallel,使用 async.each http://caolan.github.io/async/docs.html#each

async.each userList, fetchUser, (err, users) ->
于 2013-04-15T21:40:54.457 回答