0

I want to return the MySQL result into a variable. I tried the following but it's not working, as I am getting an empty variable.

const mysql = require('mysql');
const db    = require('../config/db');
const connection = mysql.createConnection(db);    

module.exports = class Categories {
   constructor (res) {
       this.res = res;
   }

   getCategories() {
       connection.query("SELECT * FROM `categories`", (error, results, fields) => {
           if (error) throw error;
           this.pushResult(results);
       });
   }

   pushResult(value) {
       this.res = value;
       return this.res;
   }
};
3
  • move this.pushResult(); inside the callback Commented Sep 25, 2017 at 15:21
  • @RolandStarke, sorry I have updated my code. Commented Sep 25, 2017 at 15:31
  • @RolandStarke still having the problem. Commented Sep 26, 2017 at 12:53

1 Answer 1

1

Just made a callback function first:

var Categories = {

    getCategories: function (callback) {
        connection.query("SELECT * FROM `categories`", (error, results, fields) => {
            if(error) { console.log(err); callback(true); return; }
            callback(false, results);
        });
    }

};

And then used it with route:

app.get('/api/get_categories', (req, res) => {

    categories.getCategories(function (error, results) {
        if(error) { res.send(500, "Server Error"); return; }
        // Respond with results as JSON
        res.send(results);
    });

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

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.