You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var http = require('http');
var result = [];
for(var i=0;i<3;i++) {
http.get(process.argv[2+i], function(res) {
var content = '';
res.on('data',function(chunk) {
content +=chunk;
});
res.on('end',function () {
result[i] = content;
});
res.on('error',console.error);
});
}
console.log(result); //result = []
There are two immediate problems I see here
You could have made your life easier by using bl module. Learning to use different npm modules is a part of learning nodeJS and carries forward the idea of modularity.
http.get() is an async function which implies the value of i might not be what you expect. Apart from that, javascript doesn't have block scope like other languages which messes up how the variable is passed around as well.
Try doing this with a forEach method on process.argv.slice[2] and bl module.
I don't really understand why it cannot work. I don't think I understand what asynchronous really means. can someone explain this to me?
var http = require('http');
var result = [];
for(var i=0;i<3;i++){
http.get(process.argv[2+i], function(res){
var content = '';
res.on('data',function(chunk){
content +=chunk;
});
res.on('end',function (){
result[i] = content;
});
res.on('error',console.error);
});
}
console.log(result); //result = []
The text was updated successfully, but these errors were encountered: