yevg
yevg

Reputation: 1976

Multiple dependent SQL queries in Node.js

Im trying to build an app which requires that I make more than one query per view/controller.

Im trying to do the asynchronously using a nested structure, but the sql result comes up undefined in the inner closure.

This is the function Im using to do this:

var conn = db.config(mysql);

function run_queries(conn,callback) {

    conn.query(sql1, var1, function(err, res1) {

        if(err){ callback(err); return; }

        console.log(res1);     // RETURNS SUCCESSFULLY!

        conn.query(sql2, var2, function(err, res2) {

            if(err){ callback(err); return; }

            console.log(res2); // UNDEFINED :(

            callback(null, res2);

        });

    });

}

run_queries(conn,function(err, result){

    console.log(result);       // UNDEFINED :(

});

I have checked my SQL and it is without errors. If I swap sq1 with sq2, the outer closure returns the correct query for sq2.

The inner closure just isnt returning a query.

Upvotes: 1

Views: 830

Answers (1)

Yogesh Patel
Yogesh Patel

Reputation: 314

Async is a very useful for an asynchronous call. You can make your code well maintained using an async module.

Example of your code using async.parallel

var conn = db.config(mysql);
var async = require('async');

function run_queries(conn, cb) {


    async.parallel({

      res1: function (cb) {

        conn.query(sql1, var1, function (err, res1) {
          if (err) { cb(err) }
          else { cb(null, res1) }
        })
      },
      res2: function (cb) {

        conn.query(sql2, var2, function (err, res2) {
          if (err) { cb(err) }
          else { cb(null, res2) }
        })
      }
    },
    function (err, result) {
      if (err) { cb(err) }
      else { cb(null, result) }
    })

}

run_queries(conn, function (err, result) {
  console.log(result);       // UNDEFINED :(
  // GET OBJECT OF res1 AND res2
});

Upvotes: 2

Related Questions