javascript - Wating for all finished request in a loop with node request -


i use node request ajax package. so, have loop, in every iteration makes request server.

// realitems needs complete value of items assigned var realitems;  var items = []; _.foreach(json.parse(body), (value, key) => {   request('myurl/' + id, (error, response, body) => {     items = json.parse(body)   }); }); 

how can bundle requests request package, can assign value of items variable realitems @ end?

// edit:

i use react js, in case realitems state, , can't trigger in every loop iteration, because render triggers on every setstate

there number of ways approach this. here's brute force method not preserve order of results:

var items = []; var cnt = 0; _.foreach(json.parse(body), (value, key) => {   ++cnt;   request('myurl/' + value.id, (error, response, body) => {     items.push(json.parse(body));     // if requesets done     if (--cnt === 0) {         // process items here results done     }   }); }); 

here's version uses bluebird promises:

var promise = require('bluebird'); var request = promise.promisify(require("request")); promise.promisifyall(request);  var promises = []; _.foreach(json.parse(body), (value, key) => {     promises.push(request('myurl/' + value.id)); }); promise.all(promises).then(function(results) {     // requests done, data requests in results array     // , in order requests made }); 

and, here's little bit simpler bluebird promises method uses bluebird iterator:

var promise = require('bluebird'); var request = promise.promisify(require("request")); promise.promisifyall(request);  promise.map(json.parse(body), function(value) {     return request('myurl/' + value.id); }).then(function(results) {     // requests done, data in results array }); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -