Sunday, 23 April 2017

NodeJS Callback and Loops

Please help me fix the code. When a route called /search is specified the following have to be done.

1.Get location and bgroup as input

2.Search DB using moongoose and find the data with similar bloodgroup as bgroup and save it into data variable.

3.Use google distancematrix api to check if the data in data variable is within 200 kms of distance with refernece to location variable. data variable has longitude and 'latitude' in it.

4.Save all the data with matching criteria to variable selecteddonors[] and their respective distance from location in donordistance[]

5.Return both the variables as response

  router.post('/search', function (req, res, next) {
    location = req.body.loc;
    bgroup = req.body.bgroup;
    var selecteddonors = [];
    var donordistance = [];
    Donor.searchByBgroup(bgroup, function (err, data) {
        if (err) {
            return res.json({
                err_desc: "Something went wrong"
            });
        } else {
            var k = 0;
            var i = 0;
            for (i = 0; i < data.length; i++) {
                var options = {
                    host: 'maps.googleapis.com',
                    path: 'https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=' + location + '&destinations=' + data[i].latitude + ',' + data[i].longitude + '&key=AIzaSyD4M1TkzIl0nyKObyXtrCOgHJpN_BDPb6A',

                }
                var count = i;

                distanceapi = function (response) {
                    var result = '';
                    response.on('data', function (chunk) {
                        result += chunk;
                    });
                    response.on('end', function () {
                        result = JSON.parse(result);
                        distance = result.rows[0].elements[0].distance.text;
                        distance = distance.replace(/ km/, '');

                        if (distance < 190) {
                            selecteddonors[k] = data[count];
                            donordistance[k] = distance;
                            k++;

                            returndata(count, data.length);
                        }
                    });
                }
                https.request(options, distanceapi).end();
            }
        }
    })

    function returndata(i, length) {
        if (i == length-1) {
            console.log(i)
            res.json({
                data: selecteddonors,
                distance: donordistance
            })
        }
    }
})

The counter variable i loops ahead before the contents of the loop are executed



via Karthik S Kumar

No comments:

Post a Comment