async.waterfall method in express js

913 Views Asked by At

Issue:

I am using express.js to fetch the data from database and display it in json format.

But when run the code in node js,an empty array(ganttresult) is displayed and when I refresh the browser again,I am getting the required result.

So,I have used async.waterfall method for the sequential execution of my code but same problem persists.

Please advice

var ganttresult= new Array();
    app.get('/get',cors(), function(request,response) {

    async.waterfall([
     function(result) {
    connection.query("SELECT id FROM Gantt",function(err, rows) {
        if (err) {
        console.log('error in fetching  ' + err);   
      }
      else{  
      var all_id=rows;  

      for(var j=0;j<all_id.length;j++){

        connection.query("SELECT id,tailName FROM Gantt where id= '"+all_id[j].id+"'",function(err, rows) {
         if (err) {
        console.log('error in fetching  ' + err);   
      }
      else{  
          var jsonString1=rows;

        var set_id=jsonString1[0].id;


        connection.query("SELECT itemId,name,start,end FROM GanttFlight  where id= '"+set_id+"'",function(err, rows) {
             if (err) {
        console.log('error in fetching  ' + err);   
      }
      else{  
        var jsonString2=rows;
         var gantt1=new Object();
        gantt1.id=jsonString1[0].id;
        gantt1.name=jsonString1[0].tailName;
        var series = new Array();
        if(jsonString2.length>0){   
        for(var i=0;i<jsonString2.length;i++){
         var gantt2=new Object();    
        gantt2.item=jsonString2[i];
        series.push(gantt2);
    gantt1.series=series;

        }
        }
        else{
        gantt1.series=[];
        }


    ganttresult.push(gantt1);

          }    
     });



    }  
     });
     }
    var result= JSON.stringify(ganttresult);
    ganttresult=[];
    response.send('{\"data\":'+result+'}');
    response.end();

     }
     });
    }
     ],   function(err) {
          if(err){
          console.log(err);
          }
        }

);
});
1

There are 1 best solutions below

1
On

I was re-writing your code to use async.waterfall correctly with async.map but I am spending too much time on it.

Here is how what I've done https://gist.github.com/bulkan/7800715

Note that it's not complete.