简体   繁体   English

从带有promise / resolve和async / await的函数返回MySql结果

[英]Returning MySql results from a function with promise/resolve and async/await

Edit: Question answered. 编辑:回答的问题。 Code is correct, just need to iterate through the results or access each element individually. 代码是正确的,只需要遍历结果或分别访问每个元素即可。

I'm writing a Discord bot with MySql. 我正在用MySql编写Discord机器人。 I need to check a table for the existence of the user before I can do other processing. 在执行其他处理之前,我需要检查用户是否存在表。 The main body (not shown here) establishes the connection and collects the user commands, invoking the appropriate module. 主体(此处未显示)建立连接并收集用户命令,从而调用适当的模块。 In this case, args[0] would have the value to search the table. 在这种情况下,args [0]将具有搜索表的值。 The timing of the promise and await lines seems to be correct, as "Results" is printed after testUser returns. promise和await行的时间似乎是正确的,因为在testUser返回之后将显示“结果”。 However, results is returning [object Object] instead of the rows (the table is not empty). 但是,结果返回的是[object Object]而不是行(表不为空)。 Shouldn't resolve(rows) inside the function return the selected rows? 函数内部不应该解析(行)返回选定的行? I'm trying to avoid adding extra modules if I don't have to. 如果没有必要,我试图避免添加额外的模块。

const discord = require("discord.js");
const mySql = require("mysql");

module.exports.run = async (bot, message, args, conn) => {

const results = await testUser(args[0], conn);
console.log("Results: " + results);
}

function testUser(userName, conn) {
    return new Promise((resolve, reject) => {
        conn.query(`SELECT * FROM user_master WHERE user_name = 
    '${userName}'`, (err, rows) => {
            if(err) reject(err);
            else resolve(rows);
        });
    });
}

The returned Object contains the result of the query and can be queried as mentioned in the comments. 返回的Object包含查询的结果,可以按照注释中的说明进行查询。 To give a complete example, this would be your code including looping the returned result: 举一个完整的例子,这将是您的代码,包括循环返回的结果:

const discord = require("discord.js");
const mySql = require("mysql");

module.exports.run = async (bot, message, args, conn) => {

  const results = await testUser(args[0], conn);
  results.forEach((row) => { 
    console.log(row); 
  });
}

function testUser(userName, conn) {
    return new Promise((resolve, reject) => {
        conn.query(`SELECT * FROM user_master WHERE user_name = 
    '${userName}'`, (err, rows) => {
            if(err) reject(err);
            else resolve(rows);
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM