javascript - How to asynchronously do multiple REST API requests in node.js? -


what want do multiple remote rest api requests, want each request done sequentially, 1 after another. read async.js way this.

as not know how many times have request, using async.whilst(). idea stop requesting once api returns 0 posts. here code far (for testing purposes limited loop run 5 times only).

var request = require('request'); var async   = require('async');  var apikey  = 'api-key-here';  var = 0; var continuewhilst = true; async.whilst(   function test() { return continuewhilst; },   dothiseverytime,   function (err) {     // done   } );  function dothiseverytime(next) {    requrl = 'http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=' + apikey + '&offset=' + i*20;      request(     requrl,     function (err, resp, body) {       if(!err && resp.statuscode == 200) {         var resultasjson = json.parse(body);               console.log(requrl);                 console.log("request #" + + " done");     }   });    i++;   if (i===5) {     continuewhilst = false;   }   console.log("iterating, i= " + i);   next(); } 

the test output this:

iterating, i= 1 iterating, i= 2 iterating, i= 3 iterating, i= 4 iterating, i= 5 http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80 request #5 done http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80 request #5 done http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80 request #5 done http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80 request #5 done http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=api-key-here&offset=80 request #5 done 

the request method somehow taking account final i value of 80. did wrong, , how fix this?

the problem occurring because requrl variable has no var, , not belong dothiseverytime scope. making requests @ once, since not waiting request complete before calling next. these 2 things leading request happen 5 times @ same time same url. try following:

function dothiseverytime(next) {     var requrl = 'http://api.tumblr.com/v2/blog/testsite.com/posts/text?api_key=' + apikey + '&offset=' + i*20;        request(requrl, function (err, resp, body) {         if (!err && resp.statuscode === 200) {             var resultasjson = json.parse(body);                   console.log(requrl);                     console.log("request #" + + " done");         }          += 1;          if (i === 5) {             continuewhilst = false;         }          console.log("iterating, i= " + i);          // in callback request now.         next();     }); } 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -