【发布时间】:2022-02-01 14:36:45
【问题描述】:
我尝试从 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);
});
你能告诉我这段代码有什么问题吗?
【问题讨论】:
-
你想达到什么目的?为什么不能使用异步库或承诺?
-
@Andrius 我是 nodejs 的新手,我正在尝试解决 learnyounode 的问题。问题想在没有任何库的情况下解决。
标签: node.js asynccallback