franco
franco

Reputation: 151

Nested callbacks in a loop

I'm facing this nested resource access to mongodb in Node.JS

I need to access to resources (let's call "resource_a") and their related sub-resources of the "resource_a" (let's call "resource_b"). I have a set of resource_b for each resource_a.

The code above is not working since it calls the callback on the first iteration. What is the best choice to get callback called as soon as all the resourceB calls are solved? Thanks, franco

function someFunction(err, callback){
    resourceA.find({}, function(err, resources_a){
        for(var resource in resources_a) {
            resourceB.find({"resourceA_Id":resources[resource]._id}, function(err, resources_b){
             // here some operation 
             callback(null, {"result":"..."}              
        }
    });
}

Upvotes: 0

Views: 248

Answers (1)

Jerome WAGNER
Jerome WAGNER

Reputation: 22462

You need to wait until all the asynchronous subcalls are finished.

Usually this is done by using a call flow library (like https://github.com/caolan/async for instance).

you could lay out your own personal quick&dirty 'join' operation like so :

function someFunction(err, callback){
    resourceA.find({}, function(err, resources_a){
        var waiting = resources_a.length;
        for(var resource in resources_a) {
            resourceB.find({"resourceA_Id":resources[resource]._id}, function(err, resources_b){
             // here some operation 
             waiting--;
             if (waiting == 0) {
               callback(null, {"result":"..."}
             }              
        }
    });
}

(please note that this has not been tested, is not handling the case when resource_a is empty and is optimistic about the fact that all calls to resourceB will call their respective callbacks)

Upvotes: 1

Related Questions