Wednesday, August 14, 2019

NodeJs , MySql Wait For Query Result

Hello,

One major issue we face while working with NodeJs and MySql is waiting for query result. When you have nested queries or you have to use for loop inside query result and wait for it's output. Because NodeJs MySql uses async function to give you query result and by the time you get the result the script finish execution.

In this blog I am going to mention one of the method I have used in one of my project. There can be various other ways for it.

First of all we have to import async plugin in your node app and add it to your script.

var async = require('async');

Now, lets assume here is your first query.

const result = connection.query('SELECT * FROM TABLE1', async function(err, rows, fields) {

});

Now this query result you have to do loop and have more queries.

let resultRows = Array();
const result = connection.query('SELECT * FROM TABLE1', async function(err, rows, fields) {
     async.each(rows, function (row, callback) {
          connection.query('SELECT * FROM TABLE 2', function(err, innerRow){
                 resultRows.push(innerRow);
                 callback(null);
          });
     }, async function () {
            //This is the final function which get executed when loop is done.
            const response = {
                statusCode: 200,
                headers: {
                "Access-Control-Allow-Origin" : "*" // Required for CORS support to work
              },
                body: JSON.stringify({
                  success: true,
                  data: resultRows
                })
              };
              callback(null, response);
    });
});

As you can see in above code, after first query is executed we are using async each for the loop.
In second query result function we are returning null callback. Once the loop is executed and all the null call backs are return it will call the final function where you will get your result rows. There you can process the result.

No comments:

Post a Comment