我正在使用express with node for rest api,我需要运行for循环来确定输出json。我的路线文件看起来
var Redis = require('ioredis')
var redis = new Redis({
port: 6379,
host: '127.0.0.1',
family: 4,
password: 'password',
db: 0
});
var Jsonresult = {};
var process = function(lat,lon,dist,unit)
{
Jsonresult.result = 'success';
var vehicle_type = new Array('small','medium');
vehicle_type.forEach(function(vehicle, index, arr)
{
redis.georadius ( vehicle,lat,lon ,dist,unit,'WITHCOORD','WITHDIST',function( ERR , Result )
{
if (ERR)
{
console.log(ERR);
}
Jsonresult[vehicle] = Result;
}) ;
})
return Jsonresult;
}
router.get('/:lat/:lon/:dist/:unit', function(req, res, next) {
var lat = req.params.lat;
var lon = req.params.lon;
var dist = req.params.dist;
var unit = req.params.unit;
res.json(process(lat,lon,dist,unit));
});
module.exports = router;
我期望的json输出是
{"result":"success","small":[["driver_1","0.2779",["56.507199704647064","-0.12500104133338397"]],["driver_2","0.2782",["56.50730162858963","-0.12500104133338397"]]],"medium":[]}
但我只是
{"result":"success"}
代码中有什么问题?
答案 0 :(得分:6)
这样:
vehicle_type.forEach(function(vehicle, index, arr) {
Jsonresult[vehicle] = true;
})
并在调用result
..
res.json()
作为回应
res.json(Jsonresult);
答案 1 :(得分:0)
vehicle_type.forEach(function(vehicle)
{
calls.push(function(callback){
redis.georadius ( vehicle,lat,lon ,dist,unit,'WITHCOORD','WITHDIST', function ( ERR , Result )
{
if (ERR)
return callback(ERR);
Jsonresult[vehicle] = Result;
callback(null, vehicle);
});
});
});
async.parallel(calls, function(err, result) {
if (err)
return console.log(err);
res.json(Jsonresult);
});
这最终解决了我的问题:回答here