我尝试从3个来源收集数据但这些是异步的.因此我试图计算回调.这是我为此目的而编写的代码.
var http = require('http');
var data_str1 = '';
var data_str2 = '';
var data_str3 = '';
var ended = 0;
function callback1(response){
response.on('end', function(){ended++;});
response.on('data', function(data){
data_str1 += data;
});
}
function callback2(response){
response.on('end', function(){ended++;});
response.on('data', function(data){
data_str2 += data;
});
}
function callback3(response){
response.on('end', function(){ended++;});
response.on('data', function(data){
data_str3 += data;
});
}
http.get(process.argv[2], function(response){
callback1(response);
if (ended == 3) console.log(data_str1);
});
http.get(process.argv[3], function(response){
callback2(response);
if (ended == 3) console.log(data_str2);
});
http.get(process.argv[4], function(response){
callback3(response);
if (ended == 3) console.log(data_str3); …Run Code Online (Sandbox Code Playgroud)