“ typeError:无法读取未定义的属性'username'。”

时间:2019-03-05 22:39:06

标签: javascript mysql promise discord.js userid

这是我不和谐机器人的>top10命令的代码:

const Discord = require("discord.js");

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

  const top10query = `SELECT user, points, lstmsg FROM scores WHERE guild = '${message.guild.id}' ORDER BY cast(points as SIGNED) ASC LIMIT 10`
  //const top10 = con.query(top10query)

  const query = querytxt => {
    return new Promise((resolve, reject) => {
      con.query(querytxt, (err, results, fields) => {
        if (err) reject(err);
        resolve([results, fields]);
      });
    });
  };
  const [results, fields] = await query(top10query);

  const map1 = results.map(results => `User: ${(bot.fetchUser(results.user)).username} Messages: ${results.points} Last message: ${results.lstmsg}`);
  message.channel.send(map1)
}
module.exports.help = {
  name: "top10",
  usage: "``prefix`` top10",
  description: "top 10 points",
}

“用户”的数据存储为用户ID。当我使用> top10命令时,我得到“未定义”。

undefined user

有什么想法吗?


编辑:
我尝试更换

const map1 = results.map(results => `User: ${(bot.fetchUser(results.user)).username} Messages: ${results.points} Last message: ${results.lstmsg}`);
      message.channel.send(map1)

使用

const map1 = results.map(results => `User: ${(bot.users.get(results.user.id)).username} Messages: ${results.points} Last message: ${results.lstmsg}`);

但是我遇到了这个错误:

(node:21128) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined

2 个答案:

答案 0 :(得分:0)

替换

User: ${(bot.fetchUser(results.user)).username

具有:

User: ${bot.users.get(results.user).username

答案 1 :(得分:0)

你想做

const map1 = await results.map(async result => {
        const user = await client.fetchUser(result);
        return `User: ${user.username} Messages: ${result.points} Last message: ${result.lstmsg}`; 
});