【问题标题】:How can I resolve a promised mysql query in express.js?如何解决 express.js 中承诺的 mysql 查询?
【发布时间】:2020-03-06 07:33:45
【问题描述】:

我正在尝试使用 npm 包 promise-mysql 并返回 json 数据(或字符串无关紧要),但我在使用 await/async 的 promise 链之后遇到了问题。

使用当前代码,我在 console.log 中收到 Promise { undefined },我在对用户的响应之前就有了。响应只是不向用户发送任何内容并将其关闭。任何人都可以指出如何调试它的正确方向吗?

index.js

app.get("/", async (req, res) => {
  console.log(  Promise.resolve(await getLogs())  ) 
  res.send(await getLogs());
});

mysql.js

const mysql = require("promise-mysql");

let pool;

async function startDatabasePool() {
    pool = await mysql.createPool({
    connectionLimit: 10,
    host: "xxx",
    user: "xxx",
    password: "xxx",
    database: "xxx"
  });
}

async function getDatabasePool() {
  if (!pool) await startDatabasePool();
  return pool;
}

module.exports = {
  getDatabasePool,
  startDatabasePool
};

users.js

const { getDatabasePool } = require("./mysql");

async function getLogs() {
  let pool = await getDatabasePool();

  pool.query("SELECT * from logs order by logdate desc", function(
    error,
    results,
    fields
  ) {
    if (error) throw error;
    return JSON.stringify(results);
  });
}
module.exports = {
  getLogs
};

【问题讨论】:

    标签: mysql node.js express


    【解决方案1】:

    index.js

    app.get("/", async (req, res) => {
      const result = await getLogs();
      res.send(result);
    });
    

    mysql.js

    const mysql = require("promise-mysql");
    
    let pool;
    
    module.exports.startDatabasePool = async () => {
        pool = await mysql.createPool({
        connectionLimit: 10,
        host: "xxx",
        user: "xxx",
        password: "xxx",
        database: "xxx"
      });
    }
    
    module.exports.getDatabasePool = async () => {
      if (!pool) await startDatabasePool();
      return pool;
    }
    
    // convert function as promise
    
    module.exports.executeQuery = async(params) => {
        return new Promise((resolve, reject) => {
            pool.query(params, function (error, result, fields) {
                if (error) {
                    reject(error);
                } else {
                    resolve(result);
                }
            });
        });
    };
    

    users.js

    const { executeQuery } = require("./mysql");
    
    module.exports.getLogs = async () => {
      return await executeQuery("SELECT * from logs order by logdate desc");
    }
    

    【讨论】:

    • edit this answer解释
    • 虽然不是我最终采用的解决方案,但如果您不使用现代便利变量,这是一种解决方法。
    【解决方案2】:

    首先我会尝试:

    app.get("/", async (req, res) => {
      let logs = await getLogs()
      console.log(logs) 
      res.send(logs);
    });
    

    希望对你有帮助!

    【讨论】:

    • 当我这样做时,我得到undefined 我感觉 users.js 文件不正确。我不完全确定如何返回 pool.query 承诺。我是否也使回调异步?还是只返回整个 pool.query,返回链上的所有内容?
    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多