Connect to MySql in node.js project with mvc architecture

Viewed 835

I have a node.js project with mvc architectures, I am trying to connect it to mysql database, and write a query, I get the query result, but when I try to call the function that declare the query, I get an empty result, I guess so it because of the query calling is async. in my model:

exports.getAllUsers = function () {
    con.connect(function (err) {
        if (err)
            console.log('error')
        else
            con.query("SELECT * FROM Users", function (err, result, fields) {
                if (err) throw err;
                else {
                    return result;
                }
            });
    });
}

in my controller:

exports.get_all_users = function (req, res) {
    var arr = UserModel.getAllUsers();
    res.send(arr);
}

the arr in get_all_users function is always undefined,

what can be the problem???

1 Answers

There are three options you could use in node.js.
These are simple code for demo three style, they still have a lot space for improvement.

  1. callback style
exports.getAllUsers = function (callback) {
    con.connect(function (err) {
        if (err)
            console.log('error')
        else
            con.query("SELECT * FROM Users", function (err, result, fields) {
                if (err) throw err;
                else {
                    callback(result);
                }
            });
    });
}

exports.get_all_users = function (req, res) {
    UserModel.getAllUsers((result) => {    
        res.send(result);
    });
}
  1. promise style
exports.getAllUsers = function () {
    return new Promise((resolve, reject) => {
        con.connect(function (err) {
            if (err)
                console.log('error')
            else
                con.query("SELECT * FROM Users", function (err, result, fields) {
                    if (err) throw err;
                    else {
                        resolve(result);
                    }
                });
        });
    })
}

exports.get_all_users = function (req, res) {
    UserModel.getAllUsers().then(result) => {    
        res.send(result);
    });
}
  1. async-await style promise style
exports.getAllUsers = function () {
    return new Promise((resolve, reject) => {
        con.connect(function (err) {
            if (err)
                console.log('error')
            else
                con.query("SELECT * FROM Users", function (err, result, fields) {
                    if (err) throw err;
                    else {
                        resolve(result);
                    }
                });
        });
    })
}

exports.get_all_users = async function (req, res) {
    const result = await UserModel.getAllUsers();
    res.send(result);
}
Related