我尝试从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); });
你能告诉我这段代码有什么问题吗?
这是我的解决方案.我已经测试过它的确有效.
var http = require('http'); var concat = require('concat-stream'); var urls = []; var responses = []; var count = 0; for (var i = 2; i < process.argv.length; i++) { urls.push(process.argv[i]); } function readResponse(index) { http.get(urls[index], function(response) { response.pipe(concat(function(data) { responses[index] = data.toString(); count++; if (count == 3) { responses.forEach(function(response) {console.log(response);}); } })); }); } for (var i = 0; i < urls.length; i++) { readResponse(i); }