javascript - 如何让函数在执行之前等待其他函数完成
问题描述
我一直在参考该线程的第一个和第二个答案,以尝试将异步函数引入我的程序中。我试图在构建嵌入之前收集用户输入,然后发送回我的不和谐服务器。我尝试了几种不同的方法,但没有取得任何进展。这是我现在所拥有的:
///// 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 中的工作方式有误解,但我觉得根据我从链接帖子中看到的答案,我遵循了正确的语法。
谢谢你的帮助。
解决方案
你需要返回你的承诺
async function collector(message,limit)
{
return message.channel....
//else
return collector(limit);
推荐阅读
- javascript - 有没有办法使用将数据存储在 JSON 文件中的 JS 变量?
- debugging - IE 使用对 console.log/error/warn/info 的引用停止脚本执行
- excel - 将图表源数据移动到 1 列?VBA
- reactjs - React 中的 Firebase 时间戳
- javascript - 复制主文件夹下的特定文件夹
- graph - 点密度的替代方案
- python - 如何在python中将两个类别列表添加到字典中
- amazon-web-services - AWS EC2 实例给出 502 Bad Gateway 错误
- laravel - 如何在 Laravel Nova 中显示加密字段值?
- facebook-pixel - Facebook Pixel 未在所有页面上触发