1

I am new to node js. In my app, I am querying the MySql DB and process and view the processed results using node js. If my query returns null data then I do another query and do the process. But my res.send(finaldate) code gets executed before the functional process gets complete. How to solve this. res.send(finaldata) executes first before the "do require stuff for finaldata" ;

var finaldata ={};
//first query
var result = connection.query('myquery', function(err, data_rows){
if(!err){
  //second
  //doing one more Query for some other records from DB (second query)
  connection.query('myquery', function(err, rows, fields){
   if(0 < rows.length){
     finaldata = //do require stuff for finaldata 
   }
   else{
      //third
      //do the second query with some condition
      connection.query(queryText, function(err, rows, fields) {
            finaldata = //do require stuff for finaldata 
      })
  }
 res.send(finaldata);

  });
 }

});

4 Answers 4

1

Welcome to NodeJS and the world of asynchronous computing!

The problem is that res.send executes before the 2nd connection.query has completed. To remedy this you put the res.send inside the callback.

var result = connection.query('myquery', function(err, data_rows) {
    if (!err) {
        //second
        //doing one more Query for some other records from DB (second query)
        connection.query('myquery', function(err, rows, fields) {
            if (0 < rows.length) {
                // do something
                res.send( /* send something*/ );
            } else {
                //third
                //do the second query with some condition
                connection.query(queryText, function(err, rows, fields) {
                    // do something
                    res.send( /*send something*/ ); // 2nd res.send
                })
            }

        });
    }

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

Comments

1

use res.send in if and else conditions

var finaldata = {};
var result = connection.query('myquery', function(err, data_rows) {
    if (!err) {
        connection.query('myquery', function(err, rows, fields) {
            if (0 < rows.length) {
                finaldata = //some value
                res.send(finaldata);
            } else {
                connection.query(queryText, function(err, rows, fields) {
                    finaldata = //some value
                    res.send(finaldata);
                })
            }
        });
    }
});

Comments

0

You need to simply move the res.send() call into the callback of the second query like this:

connection.query('myquery', function(err, rows, fields){
if(0 < rows.length){
  finaldata = //do require stuff for finaldata 
  res.send(finaldata); //<---If data
}
else{
  //third
  //do the second query with some condition
  connection.query(queryText, function(err, rows, fields) {
        finaldata = //do require stuff for finaldata 
        res.send(finaldata); // <--- If no data
   })
}

Comments

0

While the accepted answer is surely correct, I personally find it syntactically easier to wrap the query command into a Promise(), i.e.:

connection.queryPromiser = function(sql, args) {
    return new Promise(function(resolve, reject) {
        connection.query(
            sql,
            args,
            function(err, results, fields) {
                if (err) {
                    reject(err);
                } else {
                    resolve( {"results": results, "fields": fields} );
                }
            }
        );
    });
};

Then you can accomplish your res.send like so:

connection.queryPromiser("SELECT id FROM users WHERE username = ?", [ "Sami" ])
.then(function(data) {
    if (data.results.length) {
        return connection.queryPromiser("SELECT * FROM user_data WHERE user_id = ?", [ data.results[0].id ])
        .then(function(data) {
            if (data.results.length) {
                return data.results[0];
            } else {
                return "no user_data";
            }
        });
    } else {
        return "no user";
    }
}).then(res.send)
.catch(console.error);

Technically, anything you can accomplish with promises can be accomplished with callbacks; I just find it easier to encapsulate things as promises.

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.