Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

learnyounode #9 Async #2013

Closed
EliechCai opened this issue Feb 17, 2017 · 1 comment
Closed

learnyounode #9 Async #2013

EliechCai opened this issue Feb 17, 2017 · 1 comment

Comments

@EliechCai
Copy link

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 = []

@vcidst
Copy link

vcidst commented Feb 22, 2017

Fixed and indented your code for you,

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants