You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 ?
The text was updated successfully, but these errors were encountered:
muthuvenkat
changed the title
Why one works and other doesn't work to async juggling work?
Why one works and other doesn't work to async juggling?
Dec 26, 2019
I personally find the for loop confusing. Perhaps this will provide you with some clarity:
'use-strict';consthttp=require('http')consturl1=process.argv[2];consturl2=process.argv[3];consturl3=process.argv[4];// see notesgetContents(url1,function(){getContents(url2,function(){getContents(url3);});});functiongetContents(url,callback){http.get(url,function(res){letrawData="";res.setEncoding('utf8');res.on('error',function(err){returnconsole.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
This solution works
Where as this one doesn't work
The only difference the method **getData(i) ** , why one works and other doesn't
any ideas ?
The text was updated successfully, but these errors were encountered: