Wednesday 3 May 2017

why isn't my forEach function working on all arguments in this node script?

I'm attempting a solution to juggling async for the Learn You Node workshop. It isn't required, but I'm trying to make my solution modular.

Here is my main file: (solution.js)

var url1 = process.argv[2];
var url2 = process.argv[3];
var url3 = process.argv[4];
var printContents = require('./printContents.js');

var urls = [url1, url2, url3];

urls.forEach(function(url){
    printContents(url, function(err, data){
    if (err){
        throw err;
    }
    console.log(data)
    });     
})

and the helper module (printContents.js)

var http = require('http')

module.exports = function(url, cb){
    var result = "";
    http.get(url, function(response){
    response.setEncoding('utf8')
    response.on('data', function(val){
        result+=val;
    });
    response.on('end', function(){
        cb(false, result);
    });
    });
}

My problem is that this solution only prints the contents from one of the urls, not all three. Why isn't the forEach function working over the entire array?

1.  ACTUAL:    "Lets throw a grouse heaps he hasn't got a strewth. Gutful of pozzy heaps get a dog up ya ya. Watch out for the grog where as cross as a sickie. "
1.  EXPECTED:  "Lets throw a grouse heaps he hasn't got a strewth. Gutful of pozzy heaps get a dog up ya ya. Watch out for the grog where as cross as a sickie. "

2.  ACTUAL:    "Grab us a postie when as stands out like gutta. She'll be right crook bloody lets throw a no dramas. Shazza got us some rack off with it'll be pretty spiffy. "
2.  EXPECTED:  "As cunning as a ratbag where flat out like a rip snorter. She'll be right kindie my gutful of rubbish. She'll be right mickey mouse mate to mad as a bushranger. "

3.  ACTUAL:    "As cunning as a ratbag where flat out like a rip snorter. She'll be right kindie my gutful of rubbish. She'll be right mickey mouse mate to mad as a bushranger. "
3.  EXPECTED:  "Grab us a postie when as stands out like gutta. She'll be right crook bloody lets throw a no dramas. Shazza got us some rack off with it'll be pretty spiffy. "

4.  ACTUAL:    ""
4.  EXPECTED:  ""



via David J.

No comments:

Post a Comment