如何让包含select查询的函数返回结果在整体函数返回中-Node MySQL(npm包)

问题描述 投票:0回答:1

我今天联系您是因为我遇到了一个阻碍我前进的错误。我的问题如下,我的代码完全用 OOP 完成,问题出在我的类的异步方法中。问题函数称为 getDatabaseValues 并包含 MySQL 的选择查询。问题如下,当我尝试在 getDatabaseValues 函数的一般返回中返回选择查询的结果时,结果是未定义的,而如果我在 getDatabaseValues 中对结果进行 console.log 则没有问题。这是我的 getDatabaseValues 方法的代码:

// Asynchronous method to retrieve information from the database
async getDatabaseValues() {
  return new Promise(async (resolve, reject) => {
    try {
      // Create a DatabaseManager instance
      const databaseManager = new DatabaseManager();
      // Create a database connection
      await databaseManager.connect();

      // Retrieve the contents of the live table
      const request = "SELECT * FROM live";
      databaseManager.connection.query(request, (error, results) => {
       // Close the connection after making the request
       databaseManager.close();

       // If an error occurred, reject it
       if (error) {
         reject(error);
        } else {
         // Resolve the promise with the results retrieved from the database
         resolve(results[0]);
        }
      });
    } catch (error) {
      // If an error occurred during connection, reject it
      reject(error);
    }
  });
}

可以以这种形式留下代码吗?我应该改变什么?我使用的是 Node MySQL 查询方法吗?

我尝试用 Promise 返回结果,希望解析将使结果在代码中的任何地方都可用,但事实并非如此!我希望 getDatabaseValues 从选择查询中返回结果,并以这种形式在代码中的任何位置访问结果:

const databaseValues = await this.getDatabaseValues();
// If the result contains a title field, be able to use it in this way
const title = databaseValues.title; 

了解了 Stackoverflow 社区的力量后,我决定提出我的第一个问题。希望能得到一些帮助。预先感谢您,祝您有愉快的一天!

mysql node.js oop npm node-mysql
1个回答
0
投票

异步函数已经返回 Promise。

所以你在这里返回一个承诺的承诺。

尝试将

async
替换为
function

© www.soinside.com 2019 - 2024. All rights reserved.