asynchronous - async in for loop in node.js without using async library helper classes -


this question has answer here:

i beginner node.js. trying out examples 'learnyounode' tutorial. trying write program takes 3 url parameters , fetches data urls , displays returned data in order in urls provided.

var http = require('http'); var bl = require('bl'); var url = []; url[0] = process.argv[2]; url[1] = process.argv[3]; url[2] = process.argv[4]; var data = []; var remaining = url.length; for(var = 0; < url.length; i++){     http.get(url[i], function (response){         response.setencoding('utf8');         response.pipe(bl(function (err, chunk){             if(err){                 console.log(err);             }                    else{                 data[i] = chunk.tostring();                  console.log(data[i]);                 remaining -= 1;                 if(remaining == 0)  {                     for(var j = 0; j < url.length; j++){                         console.log(data[j]);                     }                                    }                            }                    }));             });  } 

i have 2 console.log statements in program. output follows:

it'll chunder lets throw ford. we're going durry mad cooee . shazza got apples come strides. mad swag when dog y roo. it'll rapt piece of piss cunning trackie dacks. cross bogged watch out boardies. cunning digger fla min lets roo bar. dry piker piece of piss hasn't got joey.  lets throw strides mate we're going digger. undefined undefined undefined 

it seems data correctly fetched , stored in 'data' array still displays undefined. idea why happening? in advance!

this common issue in async programming in node.js or in browser. main issue have loop variable i not want time later when async callback called. then, for loop have run end of loop , i @ end value response callbacks.

there numerous ways solve this. can use closure close on i value , make uniquely available each callback.

var http = require('http'); var bl = require('bl'); var url = []; url[0] = process.argv[2]; url[1] = process.argv[3]; url[2] = process.argv[4]; var data = []; var remaining = url.length; for(var = 0; < url.length; i++){     // create closure here uniquely capture loop index     // each separate http request     (function(index) {         http.get(url[index], function (response){             response.setencoding('utf8');             response.pipe(bl(function (err, chunk){                 if(err){                     console.log(err);                 }                        else{                     data[index] = chunk.tostring();                      console.log(data[index]);                     remaining -= 1;                     if(remaining == 0)  {                         for(var j = 0; j < url.length; j++){                             console.log(data[j]);                         }                                        }                                }                        }));                 });      })(i); } 

if node.js programming, find want learn how use promises because very, handy controlling flow , sequence of async operations.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

ios - Possible to get UIButton sizeThatFits to work? -