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

时间:2018-04-30 23:28:37

标签: javascript promise concatenation 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>

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

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

我似乎无法将msg连接到DB::query() ->fromSub(function($query) { $query->from('table') ->orderByDesc('time'); }, 't') ->groupBy('numbers') ->get(); 字符串。

1 个答案:

答案 0 :(得分:0)

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

我认为这应该有效:

&#13;
&#13;
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);
}
&#13;
&#13;
&#13;