简体   繁体   English

返回mysql查询的结果。 最终返回未定义

[英]Returning the results of an mysql-query. Ends up returning undefined

I have a function that queries my database and returns the results. 我有一个查询数据库并返回结果的函数。 However whatever I return, it is undefined. 但是无论我返回什么,它都是不确定的。

Server-code: I call my function here 服务器代码:我在这里调用函数

var express = require('express');
var DBmodule = require('./db.js');
var router = express.Router();

router.get('/topics', function(req,res){
    res.send(DBmodule.getTopics()); //Call to db.js - This returns undefined
});

db.js code db.js代码

var mysql = require('..\\node_modules\\mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'password'
});

exports.getTopics = function(){
connection.connect();
connection.query('USE db');
    var strQuery = "SELECT * FROM topics";

    connection.query(strQuery, function(err, rows){
        if(err){
            throw err;
        }else{
            return rows;
        }
    });

connection.end();
};

The thing that has me confused is that if I console.log rowswhen in the getTopics function, I get the correct results. 让我感到困惑的是,如果我在getTopics函数中使用console.log行,则会得到正确的结果。 But in the server code, all I get is undefined. 但是在服务器代码中,我得到的都是不确定的。

From my searching I figured it might have something with callback to do, but I could not get it to work anyway. 从我的搜索中,我发现它可能需要执行回调操作,但是无论如何我还是无法使它正常工作。 Any advice? 有什么建议吗?

You can not return in an async function, just pass rows to a callback: 您不能返回async函数,只需将rows传递给回调即可:

exports.getTopics = function(cb) {
    connection.connect();
    connection.query('USE db');
    var strQuery = "SELECT * FROM topics";

    connection.query(strQuery, function(err, rows){
        if (err) {
            throw err;
        } else {
            cb(rows);
        }
    });

    connection.end();
};

DBmodule.getTopics(function(rows){
    console.log(rows);
});

As Tresdin said a callback should be the solution. 正如Tresdin所说,回调应该是解决方案。 I found this ORM for Node, it works with many sql databases: 我找到了此ORM for Node,它可用于许多sql数据库:

http://docs.sequelizejs.com/en/latest/ http://docs.sequelizejs.com/en/latest/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM