1

I don't know why node js don't wait until function complete in loop. It just call to function but don't wait until it finish. Anyone know the solution with this problem

I went to get all room in the building and each of room's student in node js.

var mysql      = require('mysql');
    var dbconfig = {
       "host"     : "localhost",
       "database" : "university",
       "user"     : "root",
       "password" : ""
    };
    var connection = mysql.createConnection(dbconfig);
    exports.room = function(req,res){
       get_room(function(data){
          res.write( JSON.stringify(data) );
          res.end();
       });
    });

function to get all of room.

function get_room(callback){
   connection.query('SELECT * FROM Room', function(err, data){
      var Ldata = data.length;
      if(Ldata > 0){
          for(var i=0;i<Ldata;i++){
            var roomid = data[i]['roomid'];
            get_student(roomid,function(student){
                data[i].students = student;
            });
            /* wait get student call back complete and continue loop*/
          }
          /* wait untill loop complete*/
          callback(data);
      }
  });   
}

function to get student in room.

function get_student(roomID,callback){
   connection.query('SELECT * FROM Student WHERE roomid = '+roomID,function(err, rows) {
      callback(rows);
   });
}

I went to get sample result like below

[
    {
        "roomid": 1,     
        "room_name": "A",
        "students": [
            { "id": "001", "name": "jonh" },
            { "id": "002", "name": "richard" },
            { "id": "003", "name": "linda" }       
        ]
    },
    {
        "roomid": 2,     
        "room_name": "B",
        "students": [
            { "id": "011", "name": "swag" },
            { "id": "012", "name": "olli" },
            { "id": "013", "name": "jia" }       
        ]
    },
]
Dara Vichit
  • 590
  • 1
  • 7
  • 15

1 Answers1

0

The function is asynchronous. Use paralyze module to wait on multiple asynchronous callbacks to finish.

Sam
  • 6,414
  • 11
  • 46
  • 61