Node.js http.get response in loop -


so have following code. code must create 3 graphs, creates 1 (last):

for (var b=0; b<routers.length; b++)  {     (var a=0; a<rout.length; a++)     {        if(something==something)        {            console.log("bla bla");            var options = {                host: 'xxx',                path: '/xxxxx                port: 'xxxx'}                                 http.request(options).end();             http.get(options, function (response) {                 response.setencoding('utf8')                  response.on('data', function (data) {                     var responsearray = json.parse(data);                     console.log("we data. create graph!!!"                 })                     })        }     }  } 

so if run script first 3x "bla bla" , after 3x "we data. create graph!!!". think in case must "bla bla" , "we data. create graph!!!" , on 3x. right?? new in node.js please me.

promises one pattern doing this, not one. whether they're best pattern subject lot of debate in community. other options include async.js , using eventemitter. this, tend prefer async.js, i've used 3 patterns. prefer request.js built-in http client, because it's little easier use.

here's simple example using request.js , async.js:

var request = require('request'),     async   = require('async');  function iterator(router, next){   var options = {}; //  build options argument   request.get(options, function(e, response, data){      if(e) return next(e); // went wrong request       var json = null;      try { json = json.parse(data); }      catch (err){ next(err); // handle errors on parsing }       // if here, parsing happened fine.       console.log('parsed router:');      console.log(json);      next();    }); }  function handlefinalresults(e){   if(e) return console.log('dangit, ', e.message);   console.log('successfully got everything'); };  async.each(routers, iterator, handlefinalresults); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -