Skip to content Skip to sidebar Skip to footer

Asynchronous Function Inside A Javascript For Loop

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 asynchronousl

Solution 1:

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) {
    returnnewPromise(function(resolve, reject) {
        hostelery.getInfo(id, function(err, data) {
            if (err) returnreject(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 continuesconsole.err(err);
        returnnull;
    });
})).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.

Post a Comment for "Asynchronous Function Inside A Javascript For Loop"