0

I am trying to use async module on my nodejs application with not lucky.

Suppose i have the following:

/**
* parents=['parent1Template','parent2TEmplate',...]
* children=[[{id: 'child1Parent1'}{id: 'child2Parent1'}],[{id: 'child1Parent2"}{id: 'child2Parent2'}],...]
* 
*/
function createTemplate(parents,children){
     var final=[]
     async.each(Object.keys(parents), function(item,done){
                 if(children[item].length!==0) addChildsByParent(parents[item],children[item], function (result) {
                     final.push(result);
                 });
                 done();
     });
         console.log("Final results: "+final);
 return final;
}


function addChildsByParent (parent,childs,callback){
     var template=[];
      //some operations..        

    async.each(childs,function(child){
        Children.findone({"_id": child.id}, function (err,ch)){
              template.push(ch);
        }
    });
    return callback(template)
}

I need to get in final all results when all operations have finished. I have seen also functions as parallel and waterfall on async module but the main problem is that i need to work always with two arrays and do the query when i get the single value.

What's the best way, maybe something like this?

 async.waterfall([ 
   each()...
   async.waterfall([  
      each()...   
   ]) 
 ])

1 Answer 1

1

I would use async map instead of each to build the response array using the map callback. Also, I would use async parallel instead of waterfall to improve speed, since operations don't depend on each other and can be executed in parallel.

async.parallel({
    final : function(next) {
        async.map(Object.keys(parents), function(item,done){
            if(children[item].length!==0) addChildsByParent(parents[item],children[item], function (result) {
                done(null, result);
            });
        }, next);
    },
    template : function(next) {
        async.map(childs, function(child, done) {
            Children.findone({"_id" : child.id}, function (err, ch) {
                done(err, ch);
            });
        });
    }
}, function(error, results){
    if (!error) {
        console.log(results);
        // This will be {final:[], template:[]}
    }
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.