0

Context:

I fetched some "users". I want to know more about these specific users before returning the response, so I fetch detailed info for all users and add that to a result...then I return the result after all requests have finished. I'm having trouble using the parallel call:

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
TheHippo
  • 61,720
  • 15
  • 75
  • 100

2 Answers2

2

You can simply do a map. I'm writing it in native js but you get the picture.

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

async.parallel(usersFetchFunctions, function (err) { ... });
Max
  • 1,399
  • 13
  • 28
2

Don't use async.parallel, use async.each http://caolan.github.io/async/docs.html#each

async.each userList, fetchUser, (err, users) ->
aug
  • 11,138
  • 9
  • 72
  • 93
generalhenry
  • 17,227
  • 4
  • 48
  • 63