所以我在Node中有以下代码结构:
async.parallel({
firstTask: function firstTask(callback) {
var firstCall = makeNetworkCall();
callback(null, firstCall);
},
secondTask: function secondTask(callback) {
var secondTaskInputArguments = [1, 2, 3, 4, 5];
// want to make five parallel network calls to the same endpoint,
// with each one of these five network requests
// taking an item from the above list as input
}
},
function handler(err, results) {
var firstCallResults = results.firstCall;
// want to also grab five results from five parallel network calls in secondTask
});
在我的secondTask
中,我想向第二个端点发出五个并行请求。最好的方法是什么?我可以嵌套async.parallel
个调用(即在第二个任务中调用async.parallel
),但这会变得混乱。我也可以将五个并行调用放在外部async.parallel
中,但也很麻烦。完成这样的事情的首选方法是什么? (也许语法不同?)
答案 0 :(得分:0)
使用async.forEach
。既然你有一个参数数组,这就是它的完美案例! async.forEach在数组中的每个元素上调用提供的函数,并在调用这些函数的每个回调后回调一次。请注意,传递给async.forEach回调的任何错误都会导致它执行其回调代码。
async.parallel({
firstTask: function firstTask(callback) {
var firstCall = makeNetworkCall();
callback(null, firstCall);
},
secondTask: function secondTask(callback) {
var secondTaskInputArguments = [1, 2, 3, 4, 5];
async.forEach(secondTaskInputArguments, function secondTaskApiCalls(input, callback) {
// do a thing for each input
callback(null, response)
}, function allDone(err, result) {
// do a thing with all the results
// this is called once all results are in OR if err is ever passed
// as a truthy value
callback(null, processedResults)
})
}
},
function handler(err, results) {
var firstCallResults = results.firstCall;
// want to also grab five results from five parallel network calls in secondTask
});