【问题标题】:Getting the MySQL results to the route file获取 MySQL 结果到路由文件
【发布时间】:2015-11-10 18:01:33
【问题描述】:

有了一个名为mobile.js 的文件,我创建了一个到数据库的连接,并使用一个调用查询并返回一组手机的函数:

var mysql = require('mysql');
var pool = mysql.createPool({
    //database information
});

module.exports = 
{
    getAllModels: function()
    {
        pool.getConnection( function( err, connection )
        {
            connection.query("SELECT model FROM product", function( err, res, fie)
            {
                if( err ) throw err;
                connection.release();
                //console.log(res);
                return res;
            });
        });
    }
};

现在,取消注释上面的代码,我确实得到了一个 JSON 对象 [{model: 'LG'}, {model: 'Samsung'}, ...],但是当我尝试通过以下方式访问 index.js 路由文件中的该变量时:

var express = require('express');
var router = express.Router();

var mobileRepo = require('../repositories/mobile');

router.get('/', function(req, res, next) {
  var modeli = mobileRepo.getAllModels();
  console.log(modeli);

  res.render('index');
});

module.exports = router;

变量modeli 将是undefined

通过我的当前研究,我知道发生这种情况是因为connection.query 是一个异步/线程函数,但是我在任何地方都找不到并且试图弄清楚如何逃避它?

基本上,如何将路由和连接结果结合起来,从而允许变量提取查询结果?

我也很乐意接受任何关于该主题或 Node.js 的好读物,因为我目前正在学习它!

感谢阅读!

编辑:我什至可以看到查询结果在页面加载后进入,但我仍然不知道如何让查询等待。

Tue, 10 Nov 2015 00:42:06 GMT expressnodejs:server Listening on port 3000
undefined <--- this is calling the result from index.js
GET / 200 72.216 ms - 179
[ { model: 'Samsung' }, { model: 'LG' } ] <--- calling result from mobile.js when query is done

我想到的一件事是创建一个结果函数:

module.exports = 
{
    getAllModels: function( outcome )
    {
        pool.getConnection( function( err, connection )
        {
            connection.query("SELECT model FROM product", function( err, res, fie)
            {
                //snip
                outcome( res );
}}}};

但这不是打破了为什么 Node.js 一开始就这么快的整个想法吗?

【问题讨论】:

    标签: javascript mysql node.js asynchronous repository


    【解决方案1】:

    outcome 正是您所需要的,它被称为callback,这是使异步代码工作的正确方法。

    您还需要更改调用函数的方式。

    mobileRepo.getAllModels(function(modeli){
        console.log(modeli);
        res.render('index');
    });
    

    【讨论】:

    • 所以,我 我应该做的.. 感谢您的迟到答复!我会将其标记为已回答。
    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2015-01-21
    • 2015-11-03
    • 2015-10-12
    • 1970-01-01
    相关资源
    最近更新 更多