workshopper / learnyounode

Learn You The Node.js For Much Win! An intro to Node.js via a set of self-guided workshops.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why one works and other doesn't work to async juggling?

muthuvenkat opened this issue · comments

This solution works

const http = require('http')
const concat = require('concat-stream')

var count = 0;
var content = [];
var result = [];
for( var i = 0 ; i  < 3 ; i++) {
  getData(i)
}

function getData(i) {
  http.get(process.argv[i+2],  (res) =>{
      res.setEncoding('utf8');
      res.on('error', console.error)
      res.pipe(concat(function (data) {
        pushData(data, i) }))
  }).on('error',handleError)

}


function pushData(data, i){
  result[i] = data;
  count = count+1;
  if(count == 3)
    printAll()

}

function printAll(){
result.forEach(function (file) {
  console.log(file)
})
}

function handleError(err) {
  console.error(err)
  process.exit(1)
}

Where as this one doesn't work

const http = require('http')
const concat = require('concat-stream')

var count = 0;
var content = [];
var result = [];
for( var i = 0 ; i  < 3 ; i++) {
  //getData(i)
//}

// function getData(i) {
  http.get(process.argv[i+2],  (res) =>{
      res.setEncoding('utf8');
      res.on('error', console.error)
      res.pipe(concat(function (data) {
        pushData(data, i) }))
  }).on('error',handleError)
}


function pushData(data, i){
  result[i] = data;
  count = count+1;
  if(count == 3)
    printAll()

}

function printAll(){
result.forEach(function (file) {
  console.log(file)
})
}

function handleError(err) {
  console.error(err)
  process.exit(1)
}

The only difference the method **getData(i) ** , why one works and other doesn't
any ideas ?

I personally find the for loop confusing. Perhaps this will provide you with some clarity:

'use-strict';
const http = require('http')
const url1 = process.argv[2];
const url2 = process.argv[3];
const url3 = process.argv[4];

// see notes
getContents(url1, function () {
  getContents(url2, function () {
    getContents(url3);
  });
});


function getContents(url, callback) {
  http.get(url, function (res) {
    let rawData = "";
    res.setEncoding('utf8');
    res.on('error', function(err) {
      return console.log(err)
    })
    res.on('data', function(data) {
      rawData += data;
    });
    res.on('end', function() {
      console.log(rawData);
      callback ? callback() : null;
    })
  })
}

Notes:
The getContents function calls are synchronous. But I think that was the purpose of the exercise.

Also the getContents example are known as a callback hell. For a later stage probably something such as async await would be more useful. But for this exercise we actually