gpt4 book ai didi

javascript - for-each 循环在 await all 中同时运行。使用什么循环?

转载 作者:行者123 更新时间:2023-11-30 19:45:40 25 4
gpt4 key购买 nike

第一次制作 discord 机器人 (discord.js) 时遇到了我的 awaitMessage 函数同时运行的情况。例如,当我调用命令时,它会在每个 5 的循环中执行此操作。

这是什么元素?你有 60 秒!

这是什么元素?你有 60 秒!

这是什么元素?你有 60 秒!

这是什么元素?你有 60 秒!

这是什么元素?你有60秒!

我查看了 stackoverflow,我看到一个线程在 await 函数中使用 for-of 循​​环可能会解决这种情况,但我不知道它如何应用于我的代码。谢谢

  var i;
for(i = 0; i < 5; i++){
var random = Math.floor((Math.random() * etcList.length));
message.channel.send("What is this item? You have 60 seconds!", {files: ["./pictures/images/img"+(random+1)+".jpg"]});

const filter = m => m.content == (etcList[random].toString()) || (m.content==("skip"));
message.channel.awaitMessages(filter, {max:1, time:60000})
.then(collected => {
if(collected.first().content == ("skip")){
return message.channel.send("This question has been skipped! The answer was: " + etcList[random].toString());
}
if(collected.first().content == (etcList[random].toString())){
message.channel.send(collected.first().author + " has won! The answer was: " + etcList[random].toString());
}

})
.catch(err => {
message.channel.send("Time is up! The answer was: " + etcList[random].toString());
})
}

最佳答案

代替 message.channel.awaitMessages(...).then(...).catch(...) 在 for 循环中使用它

  try {
let collected = await message.channel.awaitMessages(filter, {
max: 1,
time: 60000
});

if (collected.first().content == ("skip")) {
return message.channel.send("This question has been skipped! The answer was: " + etcList[random].toString());
}

if (collected.first().content == (etcList[random].toString())) {
message.channel.send(collected.first().author + " has won! The answer was: " + etcList[random].toString());
}
} catch (e) {
message.channel.send("Time is up! The answer was: " + etcList[random].toString());
}

我们在这里使用 await 关键字来“等待”函数结果。您的 for 循环应该放在在其定义中使用 async 关键字的函数中

关于javascript - for-each 循环在 await all 中同时运行。使用什么循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com