如何返回查询函数中的值?

时间:2017-08-22 01:27:11

标签: mysql node.js function variables return

我刚刚开始编码Node。我有一个名称是"添加"并且函数内部有一个mysql查询。

我无法返回" row"查询函数内部的变量。

我该怎么做?

Broadcast.prototype.add = function (id) {
    var broadcast;
    mysql.query("SELECT * from Table WHERE Id='" + id + "'", function(err, row) {
        if(!err) {
            return row; //it didn't work
            broadcast = row; //it didn't work
        }
    });
};

1 个答案:

答案 0 :(得分:1)

(broadcast = row;)语句broadcast之后的代码不会被删除。 如果要将行的值分配给广播,则应使它们切换位置。但是,在您的评论中,您已经写过您希望将结果添加到阵列广播中。这就是为什么在提供的awnser中你会发现它是一个数组并且行值被添加到它。

另外,因为它在异步中运行,所以在添加值时需要一些回调函数。否则,将Broadcast.prototype.broadcast = []; Broadcast.prototype.add = function (id,cb) { // Use self or bind the function(err,row) to Broadcast instead so you can use a normal this inside that function as well var self = this; mysql.query("SELECT * FROM Table WHERE Id='" + id + "'", function(err, row){ // Check for errors if (err) {return console.log(err);} // Add the value of row to the broadcast array self.broadcast.push(row); // Run the callback function cb(); }); }; var broadcast = new Broadcast(); broadcast.add(id, callbackFunction = function(){ // Here broadcast should have a value console.log(broadcast.broadcast); }); // Here broadcast is likely not to have a value yet because mysql.query is probably executed in async. console.log(broadcast.broadcast); 数组记录为快速可能会导致“仍然”#39;空数组。

480kb