【问题标题】:Dynamic async parallel task动态异步并行任务
【发布时间】:2013-04-08 02:50:39
【问题描述】:

上下文:

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

【问题讨论】:

    标签: node.js asynchronous coffeescript


    【解决方案1】:

    你可以简单地做一张地图。 我是用原生 js 写的,但你明白了。

    var usersFetchFunctions = users.map(function (user) {
      return function () { ... }
    });
    
    async.parallel(usersFetchFunctions, function (err) { ... });
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-18
        • 1970-01-01
        • 1970-01-01
        • 2014-06-12
        • 1970-01-01
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多