2016-09-24 78 views
0

我正在构建一个nodejs应用程序。一个循环内的nodejs请求

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}); 

     } 

     }); 
    }); 
}); 

我在这里有两个问题。

  1. 我的循环运行4次,当我尝试console.log()我var它在控制台显示4次。

  2. 为什么我不能使用循环之外的请求体,我做了一些解决方法,并在if语句中做了res.render。

回答

0

你可能喜欢使用asyncjseachSeries功能,但你需要安装(npm install asyncjs --save),然后使用像

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}); 
    }); 
});