簡體   English   中英

異步/等待 function 在 Discord.js 機器人中執行兩次

[英]Async/Await function executing twice in Discord.js bot

我一直在 Node.js 中試驗 Discord 機器人。 我遇到了所有函數不是線性執行而是異步執行的問題。 我設法引入 async/await 來解決這個問題,但現在我的 function 調用執行了兩次,我不知道為什么(command.ec2-status 在給定的聊天中打印兩次,即使我只調用一次):對發送的消息做出反應的例程如下:

// Event: Message
client.on("messageCreate", msg => {

    // Extract metadata from message
    let msgServerID = msg.guildId;
    let msgChannelID = msg.channelId;
    let msgUserID = msg.author.id;
    let msgUsername = msg.author.username;

    // Select server and channel of current message
    let msgServer = client.guilds.cache.get(msgServerID);
    let msgChannel = msgServer.channels.cache.get(msgChannelID);

    // Command (!status): 
    // Check AWS instance status if server is "Dev Server"
    if (msg.content === "!ec2-status") {
        
        const thingy = async () => {

            let instanceStatuses = await getEC2Status();

            let statusText = "Instance Info: \n";
            for (const instanceID in instanceStatuses) {
                statusText += `${instanceID}: ${instanceStatuses[instanceID]}\n`;
            }

            msg.reply(statusText);
        }

        thingy();
    }
});

為了獲取我的 EC2 實例的狀態(命令的目標)而觸發的 function 如下:

// Function: Get the status of all EC2 instances
const getEC2Status = async () => {

    // Variable to store the status of all instances
    let instanceStatuses = {};

    // Retrieve instance information without previous permission check (DryRun = False)
    const results = await ec2.describeInstances({ DryRun: false }, (err, data) => {

        // Return an error if an error ocurrs
        if (err) {
            console.log("Retrieve Instance Info: Error\n", err.stack);
        }
        else {

            // Adds the info of each instance
            data.Reservations.forEach(reservation => {
                let instanceID = reservation.Instances[0].InstanceId;
                let status = reservation.Instances[0].State.Name;
                instanceStatuses[instanceID] = status;
            });

            console.log("Retrieve Instance Info: Success\n", instanceStatuses);
        }

    }).promise();

    return instanceStatuses
}

我很難理解異步/等待,所以這可能是問題所在。 但我需要有人把我推向正確的方向。 現在,我有點卡住了。

也許以下更改會有所幫助:

  • 使整個client.on function 異步,而不是僅在其中定義的單個thingy() function 。
  • 我不確定.promise()在做什么,但我認為等待你調用.promise()的東西是沒有意義的。 刪除.promise()

總而言之,因此:

// Event: Message
client.on("messageCreate", async (msg) => {

    // Extract metadata from message
    let msgServerID = msg.guildId;
    let msgChannelID = msg.channelId;
    let msgUserID = msg.author.id;
    let msgUsername = msg.author.username;

    // Select server and channel of current message
    let msgServer = client.guilds.cache.get(msgServerID);
    let msgChannel = msgServer.channels.cache.get(msgChannelID);

    // Command (!status): 
    // Check AWS instance status if server is "Dev Server"
    if (msg.content === "!ec2-status") {
        
        let instanceStatuses = await getEC2Status();

        let statusText = "Instance Info: \n";
        for (const instanceID in instanceStatuses) {
            statusText += `${instanceID}: ${instanceStatuses[instanceID]}\n`;
        }

        msg.reply(statusText);
    }
});
// Function: Get the status of all EC2 instances
const getEC2Status = async () => {

    // Variable to store the status of all instances
    let instanceStatuses = {};

    // Retrieve instance information without previous permission check (DryRun = False)
    const results = await ec2.describeInstances({ DryRun: false }, (err, data) => {

        // Return an error if an error ocurrs
        if (err) {
            console.log("Retrieve Instance Info: Error\n", err.stack);
        }
        else {

            // Adds the info of each instance
            data.Reservations.forEach(reservation => {
                let instanceID = reservation.Instances[0].InstanceId;
                let status = reservation.Instances[0].State.Name;
                instanceStatuses[instanceID] = status;
            });

            console.log("Retrieve Instance Info: Success\n", instanceStatuses);
        }

    });

    return instanceStatuses
}

如果沒有更多信息,我認為這些是最好的第一步。 祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM