1

I am trying to insert data that I get from the database to a json variable and then send it to the client, the problem is that as I get all the data from the database asynchronously I don't know when the json is correctly filled.

var geojson={ "type": "FeatureCollection",
              "features": []
    };

var routeObjects=JSON.parse(route.route);
for(var i=0;i<routeObjects.length;i++){
        hostelery.getInfo(routeObjects[i].ID, function(err, hostelery){
            if(!err) geojson.features.push(hostelery);
        });
}

So when all the data is in the geojson I would like to send it back to the client...

Any help would be appreciated...

Thank you very much.

AritzBi
  • 187
  • 2
  • 10
  • This should help http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs May 20 '14 at 23:07

1 Answers1

3

If what you're really just trying to do is to know when a bunch of async operations are done, there are multiple ways to approach the problem.

One way is to simply keep a count for when all the async operations have completed and then carry out whatever operation you want to when that count reaches its terminal value:

var geojson = {
    "type": "FeatureCollection",
    "features": []
};

var doneCount = 0;
var routeObjects = JSON.parse(route.route);
for (var i = 0; i < routeObjects.length; i++) {
    hostelery.getInfo(routeObjects[i].ID, function (err, hostelery) {
        if (!err) geojson.features.push(hostelery);
        ++doneCount;
        if (doneCount === routeObjects.length) {
            // all async operations are done now
            // all data is in geojson.features
            // call whatever function you want here and pass it the finished data
        }
    });
}

If your API supports promises or you can "promisify" the API to make it support promises, then promises are a more modern way to get notified when one or more async operations are complete. Here's a promise implementation:

First, promisify the async operation:

hostelery.getInfoAsync = function(id) {
    return new Promise(function(resolve, reject) {
        hostelery.getInfo(id, function(err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}

Then, you can it with Promise.all():

var geojson = {
    "type": "FeatureCollection",
    "features": []
};

var routeObjects = JSON.parse(route.route);
Promise.all(routeObjects.map(function(item) {
    return hostelery.getInfoAsync(item.ID).then(function(value) {
        geojson.features.push(value);
    }).catch(function(err) {
        // catch and ignore errors so processing continues
        console.err(err);
        return null;
    });
})).then(function() {
    // all done here
});

Since it looks like you're using node.js, there are also numerous async libraries that offer various features for managing async operations. Async.js is one such library.

jfriend00
  • 580,699
  • 78
  • 809
  • 825