我遇到了express.js路由问题。我想在用户打开/餐厅/地图时获得所有餐厅。问题是函数gm.geocode是异步的,因此在执行该函数之前呈现页面。我如何在正确的时间获得变量mapsData,所以当加载页面/餐厅/地图时?这样做的正确方法是什么?
var express = require('express');
var router = express.Router();
var gm = require('googlemaps');
var fs=require('fs');
var staticDB=require('./staticDB.js');
var mapsData=[];
/* GET home page. */
router.get('/', function (req, res, next) {
//not important
});
router.get('/map/', function (req, res, next) {
var counter=0;
console.log('Request URL:', req.originalUrl);
for (i = 0; i < staticDB.addresses.addresses.length; i++) {
gm.geocode(staticDB.addresses.addresses[i].street + ", " + staticDB.addresses.addresses[i].city, function (err, data){
mapsData.push({
"name": staticDB.restaurants.restaurants[counter].name,
"location": data.results[0].geometry.location
});
counter++;
}, false);
}
res.render('map', {
title: 'title',
restaurants: mapsData
});
});
module.exports = router;
答案 0 :(得分:3)
永远不要使用常规for
循环来处理异步流。有些模块可以为您处理这些场景,例如async
,甚至是承诺。在您的情况下,您的代码应如下所示,使用async.each
(我没有对其进行测试):
router.get('/map/', function (req, res, next) {
var counter=0;
console.log('Request URL:', req.originalUrl);
async.each(staticDB.addresses.addresses, function (address, cb) {
gm.geocode(address.street + ", " + address.city, function (err, data){
mapsData.push({
"name": staticDB.restaurants.restaurants[counter].name,
"location": data.results[0].geometry.location
});
counter++;
cb();
}, false);
}, function (err) {
if (err) {
return res.render('error', { error: err });
}
res.render('map', {
title: 'title',
restaurants: mapsData
});
});
});