Node.js Nodejs回调问题
我正在构建一个小应用程序,它需要对外部API进行多个HTTP调用,并将结果合并到单个对象或数组中。e、 gNode.js Nodejs回调问题,node.js,asynchronous,callback,Node.js,Asynchronous,Callback,我正在构建一个小应用程序,它需要对外部API进行多个HTTP调用,并将结果合并到单个对象或数组中。e、 g 连接到端点并获取身份验证密钥-将身份验证密钥传递到步骤 获取可用项列表项的摘要-使用auth键连接到端点并获取JSON结果-创建包含摘要结果的对象并传递到步骤3 迭代传递的对象摘要结果,并为对象中的每个项调用API,以获取每个摘要行的详细信息,然后创建一个包含摘要和详细信息的JSON数据结构 使用nodejs异步库,我可以到达步骤2,但是由于步骤3涉及多个HTTP请求,每个请求都有自己的回
有没有推荐的方法可以使用node轻松处理此类用例?处理多个回调并不容易。然而,已经有一些库可以帮助您,比如。解决方案可能如下所示:
var async = require("async");
var myRequests = [];
myArray.forEach(function(item) {
myRequests.push(function(callback) {
setTimeout(function() {
// this only emulates the actual call
callback(result);
}, 500);
});
});
async.parallel(myRequests, function(results) {
// this will fire when all requests finish whatever they are doing
});
一个简单的解决方案是计算您的回调次数:
var results = [];
function final_callback(results)
function callback(result){
results.push(result):
if (results.length == number of requests){
final_callback(results);
}
}
更合适的解决方案是使用带计数器的事件和事件发射器:
my_eventEmitter.on('init_counter',function(counter){
my_eventEmitter.counter=counter;
});
my_eventEmitter.on('result',function(result){
if( my_eventEmitter.counter == 0 ) return;
//stop all callbacks after counter is 0;
my_eventEmitter.results.push(result);
my_eventEmitter.counter--;
if( my_eventEmitter.counter == 0 ){
my_eventEmitter.emit('final_callback');
}
});
my_eventEmitter.on('final_callback', function(){
//handle my_eventEmitter.results here
})
。。。。
现在您只需执行for,但在它将init_计数器发送到事件发射器之前
my_eventEmitter.emit('init_counter',50);
for(i=0; i<50; i++) async_function_call(some_params, function(result){
my_eventEmitter.emit('result',result);
});
my_eventEmitter.emit('init_counter',50);
对于(i=0;i