javascript - foreach 中的 Discord.JS addField 不起作用

标签 javascript node.js discord.js

由于某种原因,addField 无法正常工作。没有错误,只是没有显示出来。

query 和 foreach 都很好,并且可以正常工作。我在命令中使用了那个确切的设置。它只是不适用于嵌入。

const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "testbot"
});
con.connect(err => {
if(err) throw err;
console.log("Connected to database!");
});


function statusUpdate() {

var update = bot.channels.get('5777623821454355545');
const statusEmbed = new Discord.RichEmbed();
statusEmbed.setTitle("**Current Statuss:**");
con.query("SELECT * FROM games", function(err, result, fields) {
   if(err) throw err;
    Object.keys(result).forEach(function(key) {
        var row = result[key];
        statusEmbed.addField('**' + row.name + '**' + ' - ' + '(' + row.description + ')' + ' - ' + '**' + row.status + '**');
    });
});
update.send(statusEmbed);
}

bot.on('ready', () => {
console.log('This bot is online!');
statusUpdate();
});

最佳答案

您必须在查询回调中更新 statusEmbed,因为如果不这样做,您将在 addField 尚未执行时更新它。

回调意味着查询是异步的。


基于回调的解决方案

function statusUpdate(callback) {
  const update = bot.channels.get('577762382164525066');

  const statusEmbed = new Discord.RichEmbed();

  statusEmbed.setTitle('**Current Statuss:**');

  con.query('SELECT * FROM games', function(err, result, fields) {
    if (err) {
      callback(err);

      return;
    }

    Object.keys(result).forEach((key) => {
      const row = result[key];

      statusEmbed.addField(`**${row.name}** - (${row.description}) - **${row.status}**`);
    });

    update.send(statusEmbed);

    callback(false);
  });
}

备选

function statusUpdate() {
  const update = bot.channels.get('577762382164525066');

  const statusEmbed = new Discord.RichEmbed();

  statusEmbed.setTitle('**Current Statuss:**');

  con.query('SELECT * FROM games', function(err, result, fields) {
    if (err) {
      throw err;
    }

    Object.keys(result).forEach((key) => {
      const row = result[key];

      statusEmbed.addField(`**${row.name}** - (${row.description}) - **${row.status}**`);
    });

    update.send(statusEmbed);
  });
}

关于javascript - foreach 中的 Discord.JS addField 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56270365/

相关文章:

javascript - 在 Canvas 上显示用户的文本

javascript - 什么可以抵消我的表格工作

node.js - 如何设置包含多个应用程序的 Dojo 构建流程?

javascript - Angular 应用程序转移到版本 6 错误 : 'Global is not defined'

javascript - 尝试获取 process.env node.js 时出现 SyntaxError : Unexpected token .

javascript - Discordjs bot (Nodejs) 如何使用reactjs将数据添加到DOM

javascript - 当涉及参数时避免在 render() 方法中创建函数的最佳技术

javascript - 如何使用 jQuery 动态更新 CSS 样式列表?

javascript - 获取数组中的所有元素(Javascript)

javascript - 如何找到discord机器人所连接的语音聊天