Hi there... I'm just going through the learnyounode exercises (so obviously
a complete node.js beginner!) - and was proceeding quite confidently until
I hit upon the 'juggling async' exercise. I have to admit tearing my hair
out here and eventually cheating to get the 'official answer'. More
frustrating was how close I was... and I am still not sure why mine does
not work. I apologise if I am being stupid (very likely) - but I think it
would really help my understanding to get to the bottom of this.
Anyway, what I did was this:
var http = require('http');
var bl = require('bl');
var htmls = [];
var count = 0;
for( var i = 0; i<3; i++){
http.get( process.argv[2+i], function( r ){
r.pipe(bl(function( err, buf ){
count++;
htmls[ i ] = buf.toString();
if ( count == 3 ){
print_results();
}
}))
});
}
function print_results(){
for( var j=0; j<3; j++ ){
console.log( htmls[j] );
}
}
I then run e.g.
node ex9.js http://www.google.com http://www.yahoo.com
http://www.reuters.com
and get:
undefined
undefined
undefined
To get the correct answer, all I need to do is stick the stuff in the first
'for' loop in a function and instead loop through calling the function:
for( var i = 0; i<3; i++){ get_http(i) }
function get_http(i){
http.get( process.argv[2+i], function( r ){
r.pipe(bl(function( err, buf ){
count++;
htmls[ i ] = buf.toString();
if ( count == 3 ){
print_results();
}
}))
});
}
Now it works! But why? I can see that 'i' is scoped differently in the
second (correct) arrangement, but still don't see how it is it produces
different results.
Very much appreciate any light that could be shed on this (for a complete
beginner!)
Thanks :)
--
Job board: http://jobs.nodejs.org/
New group rules:
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/nodejs/c9baf277-19bc-4d83-8b21-045dc1102079%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.