首页 > 解决方案 > 如何让函数在执行之前等待其他函数完成

问题描述

我一直在参考线程的第一个和第二个答案,以尝试将异步函数引入我的程序中。我试图在构建嵌入之前收集用户输入,然后发送回我的不和谐服务器。我尝试了几种不同的方法,但没有取得任何进展。这是我现在所拥有的:

///// Lets start here
    execute(message, args) 
    {
        embedBuilder(message);
    },
};

// Collector to collect the users input and return it to some variable
async function collector(message,limit) 
{
    message.channel.awaitMessages(response => response.author.id === message.author.id, 
        {
            max: 1,
            time: 10000,
            errors:['time'],
        })
        .then((collected) => {
            if (collected.first().content.length < limit)
            {
                message.author.send(`I collected the message : ${collected.first().content}`);
                return collected.first().content;
            }
            //else
            collector(limit);
        })
        .catch(() => {
            message.author.send("No message collected after 10 seconds.")
        })
}

async function embedBuilder(message)
{
    message.author.send("Lets get to work!\nPlease enter the title of your event. (Must be shorter than 200 characters)");
    const title = await collector(message,200); // AWAIT HERE
    message.author.send("Please enter a short description of your event. (Must be shorter than 2000 characters)");
    const description = await collector(message,2000); // AWAIT HERE
    const eventEmbed = new Discord.MessageEmbed()
    .setColor('RANDOM')
    .setTitle(title)
    .setAuthor(message.author.username)
    .setDescription(description)
    .setImage();
    message.channel.send(eventEmbed);
}

现在它根本不需要等待,将我的两个提示都传递给用户,然后一次运行 2 个收集器,所以当我输入一些东西时,两个收集器都会返回相同的东西。

例如:

Me : !plan //Prompting the discord command
Bot: Lets get to work!
     Please enter the title of your event. (Must be shorter than 200 characters)
     Please enter a short description of your event. (Must be shorter than 2000 characters)
Me : Testing
Bot: I collected the message : testing
     I collected the message : testing

谁能指出我做错了什么?我相信我可能对异步函数在 JS 中的工作方式有误解,但我觉得根据我从链接帖子中看到的答案,我遵循了正确的语法。

谢谢你的帮助。

标签: javascriptasynchronousdiscorddiscord.js

解决方案


你需要返回你的承诺

async function collector(message,limit) 
{
    return message.channel....
            //else
            return collector(limit);

推荐阅读