如何从包含数据库查询的Node.js函数返回值

时间:2014-01-18 16:26:51

标签: javascript node.js

我正在学习Node.js,而我刚刚开始使用一些MySQL连接。我有一个函数,它应该从数据库中获取一组行,它正确地执行。但是,我不知道如何在之后返回那组行。我尝试了两个选项(在下面的代码段中的注释中都有解释。

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
}

所以,问题是,如何返回ret的正确值(本例中为7)?我是否正确地构建了这个?

1 个答案:

答案 0 :(得分:10)

您需要将回调传递给您的函数。惯例是回调会将错误(或null,如果没有发生)作为第一个参数,并作为其他参数产生。

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

您现在可以按照以下方式执行以下操作:

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