webli webli - 2 months ago 5
Node.js Question

a nodejs request within a loop

i have a little app i am building in nodejs the code is:

Location.find({} ,function (err, result){
var locations = [];
result.forEach(function(listItem, i){
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + encodeURIComponent(listItem.address) + "&key=AIzaSyDQsX4Kci3xHp1xy6ZjT-5lsLNI-J-CH-8";
request(url, function(error, response, body) {

all = JSON.parse(body);


locations.push({des: result[i].placeinfo,lat: all.results[0].geometry.location.lat, lng: all.results[0].geometry.location.lng });

if (i == result.length - 1) {
res.render("index.ejs", { layout: false,locationmap:locations});

}

});
});
});


i have two problems one i that my loop runs 4 times, when i try to console.log() the i var its shows 4 time in the console.
second why cant i use the request body outside of the loop i did some workaround and did the res.render inside the if statement.

Answer

You may like to use asyncjs eachSeries function but you need to install(npm install asyncjs --save) and then use like

var async = require('asyncjs');

Location.find({} ,function (err, result){  
    var locations = [];
    async.eachSeries(result, function iteratee(listItem, callback) {
        url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + encodeURIComponent(listItem.address) + "&key=AIzaSyDQsX4Kci3xHp1xy6ZjT-5lsLNI-J-CH-8";
        request(url, function(error, response, body) {
            all = JSON.parse(body);
            locations.push({des: result[i].placeinfo,lat: all.results[0].geometry.location.lat, lng: all.results[0].geometry.location.lng  });
            callback(error, body);
        });
    }, function done() {
        res.render("index.ejs", { layout: false,locationmap:locations}); 
    });
});
Comments