foreach中的Discord.JS addField无法正常工作

时间:2019-05-23 07:44:59

标签: javascript node.js discord.js

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

查询和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();
});

1 个答案:

答案 0 :(得分:2)

您必须在查询回调中进行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);
  });
}