CairoCoder
CairoCoder

Reputation: 3207

Return MySQL result after query execution using node.js

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;
   }
};

Upvotes: 0

Views: 729

Answers (1)

CairoCoder
CairoCoder

Reputation: 3207

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);
    });

});

Upvotes: 1

Related Questions