Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LearnYouNode - Juggling Async

I read some of the same tutorial questions but i still can't understand.

I got it right with the following codes

<code>
var httpModule = require('http');
var blModule = require('bl');
var arguments = process.argv;
var urls = [ arguments[2], arguments[3], arguments[4] ];
var results = [];
var count =0;
urls.forEach(
    function(url , i)
    {       
        var printResponse = function (response)
        {   

                response.pipe(
                blModule(
                    function(err, data)
                    {
                        count++;
                        if(err)
                        return console.log(err);

                        results[i] = data.toString();
                            //if(results.length===3)
                            if(count===3)
                            {
                            for( var c=0; c < results.length; c++)
                            console.log(results[c]);
                            }

                    }
                )
            );

        }

        httpModule.get(url, printResponse);

    }
);

</code>

The part which i don't understand is if(count===3) ,i know that by checking if count == 3, i can sure that the callback function is all called. Initially i use if(results.length === 3) as i thought that would means i have all results now, but it fails, can anyone explain?

Thanks

like image 238
lai yoke hman Avatar asked Mar 16 '26 09:03

lai yoke hman


1 Answers

Its just a JS thing..

j = [] // j.length = 0
j[2] = 0 // now the j.length = 3 *magic*

what I understand is your 3rd request is the quickest :P

like image 147
Minato Avatar answered Mar 18 '26 22:03

Minato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!