gpt4 book ai didi

node.js - 动态异步并行任务

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:35 25 4
gpt4 key购买 nike

上下文:

我获取了一些“用户”。我想在返回响应之前了解有关这些特定用户的更多信息,因此我获取所有用户的详细信息并将其添加到结果中......然后在所有请求完成后返回结果。我在使用并行调用时遇到问题:

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

最佳答案

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

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

关于node.js - 动态异步并行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com