Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from Node.js function which contains DB query [duplicate]

I'm learning Node.js and I'm just starting to work with some MySQL connections. I have a function which is supposed to get a set of rows from the database, which it does correctly. However, I don't know how to return that set of rows afterwards. I tried two options (both explained in comments within the code segment below.

function fetchGameList(){
    var ret = 0;

    connection.query("SELECT * from tbl", function(err, rows, fields) {
        //some stuff happens here, and 'ret' is set to a vlue, for instance
            //ret = 7;
        //ret has the value 7 here, but if I put 'return ret' here, nothing is returned
    });

    return ret; //returns 0 because Node is asynchronous and the query hasn't finished yet
}

So, the question is, how do I return the correct value of ret (7 in this case)? Am I even structuring this properly?

like image 744
sveti petar Avatar asked Jan 18 '14 16:01

sveti petar


1 Answers

You need to pass a callback into your function. Convention is that the callback takes an error (or null if none happened) as the first argument, and results as other arguments.

function fetchGameList(callback) {
    var ret;

    connection.query("SELECT * from tbl", function(err, rows, fields) {
        if (err) {
            // You must `return` in this branch to avoid using callback twice.
            return callback(err);
        }

        // Do something with `rows` and `fields` and assign a value to ret.

        callback(null, ret);
    });
}

You can now do something along the lines of:

function handleResult(err, result) {
    if (err) {
        // Just an example. You may want to do something with the error.
        console.error(err.stack || err.message);

        // You should return in this branch, since there is no result to use
        // later and that could cause an exception.
        return;
    }

    // All your logic with the result.
}

fetchGameList(handleResult);
like image 72
qubyte Avatar answered Oct 24 '22 21:10

qubyte