【问题标题】:NodeJS - Modularising SQLite3NodeJS - 模块化 SQLite3
【发布时间】:2015-02-27 01:09:32
【问题描述】:

我喜欢在可能的情况下拆分我的代码 - 在路由中使用 SQL 让我感到畏缩。

Node JS 对我来说是新的,我现在正在学习它,但是我遇到了以下问题(页面只是挂起并且没有提供任何服务)。

以我目前的知识水平,这对我来说很有意义 - 但我想会有更好的方法来做到这一点。

感谢您抽出宝贵时间阅读本文,非常感谢您的帮助。


路线

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

var model     = require('../models/contacts.js');

/* GET contacts. */
router.get('/', function(req, res) {

  // Get data from model - RETURN THE ROWSET HERE
  model.get_names(db, function(rowset) {

    res.render('contacts', { 
      title: 'Contacts | Rhubarb',
      nav_active: "contacts",
    }, function(err, output) {
      res.status(200).send(rowset);  
    }); // res.render

  }); // model.get_names

}); // router

module.exports = router;

型号

module.exports.get_names = function(db) {

  var sql = " SELECT attr_name " +
            "      , attr_value " +  
            "   FROM contacts  a " +
            "      , contact_attributes b " +
            "  WHERE a.contact_id = b.contact_id " +
            "    AND (attr_name = 'forename' OR attr_name = 'surname')";


   db.all(sql, function(err, rowset) {

     if (err) throw err;
     return rowset;

   }); // db.all

}  // get_names

【问题讨论】:

    标签: node.js asynchronous sqlite


    【解决方案1】:

    通过添加一个实际的回调函数对其进行排序... sigh...

    module.exports.get_names = function(db, callback) {
    
      var sql = " SELECT attr_name " +
                "      , attr_value " +  
                "   FROM contacts  a " +
                "      , contact_attributes b " +
                "  WHERE a.contact_id = b.contact_id " +
                "    AND (attr_name = 'forename' OR attr_name = 'surname')";
    
    
      return db.all(sql, function(err, rowset) {
        if (err) throw err;
    
        return callback(rowset);
    
      });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 2011-04-21
      • 2015-11-07
      • 2013-06-18
      相关资源
      最近更新 更多