2016-09-24 87 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}); 
    }); 
});