导入的数据库函数不在Expressjs中返回路径内的值

时间:2017-10-26 16:41:09

标签: javascript node.js express

我正在尝试使用Expressjs制作REST API。当我开始时,我只使用了一个包含所有路由的主文件,现在我将这些路由,数据库连接和数据库方法分开在它们的文件中。

登录-db.js



const { showMessage, showError } = require("../show-message-handler");
const connection = require("../db/db");

module.exports = {
  login: function (username, password) {
    let r;
    connection.query(
      "SELECT * FROM User WHERE username = ? AND password = ?;", [username, password],
      (error, rows, fields) => {
        if (error)
          showError(error.code, "Couldn't retrieve user.");

        r = rows.length !== 0 ? true : false;
        showMessage(r);
      }
    );

    return r;
  }
}




login.js



const { showMessage, showError } = require("../show-message-handler");
const router = require("express").Router();

const { login } = require("../db-methods/login-db");

router.post("/", (req, res) => {
  let r = false;
  showMessage("Before login: => " + r);
  r = login(req.body.username, req.body.password);
  showMessage("After login: => " + r);

  res.send(String(r));
});

module.exports = router;




当我测试控制台时,打印出类似这样的内容:

// before login: false // -> r = false
// after login: undefined // -> r = undefined
// inside login function in login.js // r = true

那么要解决这个问题呢?我尝试使用异步功能,但在v6中不支持,只在v8中支持。我在运行v6的AWS的AWS Lambda中托管,所以我无法升级。

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

这应该有效,(或不):

const { showMessage, showError } = require("../show-message-handler");
const connection = require("../db/db");

module.exports = {
  login: function (username, password, callback) {
    let r;
    connection.query(
      "SELECT * FROM User WHERE username = ? AND password = ?;", [username, password],
      (error, rows, fields) => {
        if (error)
          showError(error.code, "Couldn't retrieve user.");

        r = rows.length !== 0 ? true : false;
        callback(null, r);
      }
    );
  }
}

login.js

const { showMessage, showError } = require("../show-message-handler");
const router = require("express").Router();

const { login } = require("../db-methods/login-db");

router.post("/", (req, res) => {
  let r = false;
  showMessage("Before login: => " + r);
  login(req.body.username, req.body.password, function(error, result) {
    showMessage("After login: => " + result);
    res.send(String(result));
  });
});

module.exports = router;
问题是,查询操作是异步进程,但是你立即返回r,你应该等待查询完成并使用回调