user375566
user375566

Reputation:

Dynamic async parallel task

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

Upvotes: 0

Views: 4043

Answers (2)

generalhenry
generalhenry

Reputation: 17319

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

async.each userList, fetchUser, (err, users) ->

Upvotes: 2

Max
Max

Reputation: 1459

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) { ... });

Upvotes: 2

Related Questions