Peter
Peter

Reputation: 804

Node express: not able to access data after query execution

I have a simple custom module in which all methods are supposed to return database records.

I am getting all records after running a query but when I try to assign those records to some variable then it says null. Not sure what is going on. Here is my custom module code:

module.exports = {

    mydata: {},
    all: function (req, res, next) {

        var posts = null;

        con.query("SELECT post_id,title, body from `posts`", function (err, rows, fileds) {
            if (err) {
                console.log('Error' + err);
            }
            posts = rows[0]; // assigned object object to posts but not working


            console.log('names' + posts);
        });

        console.log('my posts' + posts); // it says null/empty 
        return posts;       // empty return

    },

I am calling all methods like this in my route:

console.log("admin.js :" + postModel.all());

All are empty or null. Please guide or suggest. Am I missing anything?

Upvotes: 3

Views: 598

Answers (2)

Atish Shakya
Atish Shakya

Reputation: 561

Welcome my friend to the world of Asynchronous function. In your code the

console.log('my posts' + posts); and return posts;

are executing before the callback assigns values to the posts variable.

Also restrict yourself from using var instead use let for declaring variable works better without error for scoped functions.

Here below:

  • The async keyword declares that the function is asynchronous.
  • The await keyword basically says that lets first get the result and then move on to next statement/line. All awaits should be done inside an async functions only.
module.exports = {

mydata: {},
  all: async function (req, res, next) { //Let this be an asynchronous function
      try{
         let [rows, fields] = await con.query("SELECT post_id,title, body from `posts`");
         //let us await for the query result so stay here until there is result

         let posts = rows[0]; // assign first value of row to posts variable now
         console.log('my posts' + posts);
         return posts;
      }catch(err){
         return err;
      }
  },
}

Please take time reading up nature of Asynchronous, Non-blocking in JavaScript and how to handle them with Promises or Async/await (my personal choice).

Upvotes: 1

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

Try using async & await plus it's best practice to wrap the code in try catch, any pending promise will be resolved at the .then method or any error will be caught at the .catch of the caller/final function:

/ * Handler (or) Service (or) Whatever */

const FetchDataFromDB = require('../');

/* caller Function */
let fetchDataFromDB = new FetchDataFromDB();
fetchDataFromDB.getDataFromDB()
    .then((res) => console.log(res))
    .catch((err) => console.log(err))

/* DB Layer */

class FetchDataFromDB {

    /* Method to get data from DB */
    async getDataFromDB() {

        const getQuery = "SELECT post_id,title, body from `posts`";
        try {
            let dbResp = await con.query(getQuery);
            if (dbResp.length) {
                //Do some logic on dbResp
            }
            return dbResp;
        } catch (error) {
            throw (error);
        }
    }
}

module.exports = FetchDataFromDB;

Upvotes: 1

Related Questions