1

I'm using express with node for my rest api, I need to run a for loop to determine the output json. my route file looks

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;

and my expected json output is

{"result":"success","small":[["driver_1","0.2779",["56.507199704647064","-0.12500104133338397"]],["driver_2","0.2782",["56.50730162858963","-0.12500104133338397"]]],"medium":[]}

but i'm getting only

{"result":"success"}

whats wrong in the code ?

Dan Crews
  • 3,067
  • 17
  • 20
Vigikaran
  • 725
  • 1
  • 10
  • 27

2 Answers2

6

this way:

vehicle_type.forEach(function(vehicle, index, arr) {
   Jsonresult[vehicle] = true;
})

and pass result in response as well when calling res.json()..

res.json(Jsonresult);

narainsagar
  • 1,079
  • 2
  • 13
  • 29
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);
 });

This finaly solve my problem: answer here

Community
  • 1
  • 1
Vigikaran
  • 725
  • 1
  • 10
  • 27