-1

I am very new to node.js and here is my problem

I have a nested set of maps here(I have tried using for-each as well). All the "get..." methods nested are returning a promise defined by me. I have to loop over the data returned by the methods continuously and use it to call the next "get.." method(there is a dependency). After completing the entire nested loops, the "allobj" array should have my final result and I am trying to return it once all the looping is done. I have not had any luck so far, as an empty array gets returned.

var allobj = new Array(); 
var catcount = 0; 

//categories.forEach(function(category){    
var p = categories.map(function(category,index,array){          
catcount++;

return gettests(runid,category).then(function(tests){
//console.log(tests.sort().reverse());     //this is sync   

    //tests.forEach(function(test){
    var t = tests.map(function(test,index,array){  

        return getmetriccategories(runid,category,test).then(function(data){
       //console.log(data);

        //data.forEach(function(mc){
        var d = data.map(function(mc,index,array){  

            return getmetrics(runid,category,test,mc).then(function(data1){

                var x = data1.map(function(metric,index,array){
                            allobj.push(metric);
                            return metric;
                        });
                    });   
                });
            })
        })
    })
}) 

//return when all nested loops are done       
res.send(allobj);      
  • There are hundreds of this type of question already answered here on stack overflow. Search for "promise loop" here on stack overflow and you will find tons of related answers. Since you are already using promises, you need to gather all your promises created in a loop and `return Promise.all(allYourPromises)`. That's how you get the parent promise to not resolve until all the child promises are done. – jfriend00 Aug 04 '17 at 20:41
  • Here's one example: [Wait For Promises From a For Loop](https://stackoverflow.com/questions/32081677/wait-for-promises-from-a-for-loop/32085526#32085526). – jfriend00 Aug 04 '17 at 20:50

1 Answers1

0

Your functions getmetriccategories and getmetrics return Promises, at least, their return values seem to have a then method which is an indicator for that. This means, they work asynchronously. So, the map calls don't return the results directly, but an array of Promises. To wait for all of these Promises to be fulfilled (which means, the asynchronous functions are completed), you can use Promise.all function:

Promise.all(data.map(...))
    .then(function (result) {
        res.send(result)
    })

As you see, Promise.all returns a new Promise, so you can use then to receive the result and send it with res.send.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27