无法从节点js中的函数返回数据

时间:2018-04-28 07:10:29

标签: javascript node.js

我无法从不同的js文件中的函数返回任何数据

token.js文件:

var express = require('express');
var jwt = require('jsonwebtoken');
var md5 = require('md5');
var Super = require('../models/super');
var db = new Super();

var router = express.Router();

/* GET users listing. */
router.post('/Login', function(req, res) {
   var username = req.headers['username'];
   var password = req.headers['password'];
   var md5pass = md5(password);

   var ress = db.get('app_user',"username = '"+username+"' and password = '"+md5pass+"'",null,null);
   res.send(ress);
});

module.exports = router;

文件super.sj:

var db = require('../config/database');
class Super{
   get(table, where, order, limit){
       if(where != null && order != null && limit != null){
        db.query('SELECT * FROM $1 WHERE $2 ORDER BY $3 LIMIT $4', [table, where, order, limit], (err, result) => {
            if(err) throw err;
            return result.rows;
        });
    }
   }
}
module.exports = Super;
postman上的

无法获取任何数据或错误响应

1 个答案:

答案 0 :(得分:1)

这是假类反模式 - 你应该只导出一个函数。由于db.query是异步的,因此如果您希望能够在其他地方使用其结果,则应将get转换为Promise

var db = require('../config/database');
function get(table, where, order, limit){
  return new Promise((resolve, reject) => {
    if(where != null && order != null && limit != null){
      db.query('SELECT * FROM $1 WHERE $2 ORDER BY $3 LIMIT $4', [table, where, order, limit], (err, result) => {
        if(err) reject(err);
        resolve(result.rows);
      });
    } else reject();
  });
}
module.exports = get;

然后使用.then(或await)消费:

var express = require('express');
var jwt = require('jsonwebtoken');
var md5 = require('md5');
var get = require('../models/super');

var router = express.Router();

router.post('/Login', function(req, res) {
  var username = req.headers['username'];
  var password = req.headers['password'];
  var md5pass = md5(password);

  get('app_user',"username = '"+username+"' and password = '"+md5pass+"'",null,null)
    .then(ress => res.send(ress));
});