Friday, 26 May 2017

NodeJs multiple async calls in async function

Morning all!This is my problem : I have a database with 2 collections, to simplify they look like this :

    var classes = {  
     class:Number,
     students:[Number] }  
    var student = {
     id:Number,
     name:String }  

I also have a route that recives some data about a class (eg, accademic Year, class,etc.) and asks the classes model to return the students names. I have an easy time selecting the needed array of students but in my classes model i can't find a pretty way of asking the student model for the names. I was doing something like this in the Classes model :

mod.exports = function(someDataToRetriveClass,callback){ 
    var counter =0;    
    var studData = [];
    Classes.getStudList(function(err,res){   
        for(var i=0;i<res.length;i++){
            getStudData(res[i],function(err,res2){ 
               counter +=1;  
               studData.push(res2);
               if(counter >= res.length){callback(studData)}

            })
     }})  
}  

It's an ugly way of doing things, is there some more concise way of getting the same result?
Ps: im using mongodb and mongoose as database support.



via Filippo Bosco

No comments:

Post a Comment