discord.js:将用户名添加到字符串的问题

我使用discord.js为Discord bot编写了以下代码 . 我试图编写的代码的目的是让bot回复一个用户名列表,其id在另一个.json文件中指定 . 这就是我写的 .

if(command === "privlist")
{
    var msg = ""
    msg += "[Privileged Users]\n"

    // iterate through the array of id's
    config.privileged.forEach(function(item, index) {
        msg += index + ": ";

        // fetch the user associated with the id in the array
        client.fetchUser(item).then(User => {
            // add the name of the user into the string to be outputted
            msg += User.username + "#" + User.discriminator;
        });

        // include the user id as well
        msg += " <" + item + ">\n";
    });

    // send the message
    message.channel.send(msg);
}

机器人的预期回复应该是这样的 .

[Privileged Users]
0: Merlin#8474 <172734241136836608>
1: Spring Voltage#2118 <255109013383938048>
2: masterhunter56#2561 <243167201471889409>
3: brett#4582 <123957558133129217>

但相反,这就是我得到的 .

[Privileged Users]
0:  <172734241136836608>
1:  <255109013383938048>
2:  <243167201471889409>
3:  <123957558133129217>

我尝试在 msg += User.username + "#" + User.discriminator; 行之后添加 console.log(User.username) ,这使得名称在控制台中正确显示 .

我甚至可以在 msg += User.username + "#" + User.discriminator; 之后执行 message.channel.send(User.username) ,这将发送每个名称作为它自己的消息 .

我似乎无法将 User.username + "#" + User.discriminator 连接到 msg 字符串 .

回答(1)

2 years ago

正如Jaromanda X所说,你使用了异步函数 . 这意味着这一行: msg += " <" + item + ">\n"; 将不会等待 client.fetchUser(item).then(User 结束继续 .

我认为这应该有效:

if(command === "privlist")
{
    var msg = ""
    msg += "[Privileged Users]\n"

    // iterate through the array of id's
    config.privileged.forEach(function(item, index) {
        msg += index + ": ";

        // fetch the user associated with the id in the array
        client.fetchUser(item).then(User => {
            // add the name of the user into the string to be outputted
            msg += User.username + "#" + User.discriminator;
            // include the user id as well
            msg += " <" + item + ">\n";
        });
    });

    // send the message
    message.channel.send(msg);
}