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

标签 javascript node.js discord.js

第一次制作 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/

相关文章:

node.js - NPM 正在安装大量库

javascript - 如何修复错误无法读取未定义的属性 'trim`

javascript - 使用 discord.js 在第一个 channel 发送消息

javascript - 在动态创建的 HTML 表中搜索复选框

Javascript从字符串中获取顶级域名

javascript - 尝试将 JSON 文件放入 JS 数组中

javascript - 使用 firebase auth 获取用户详细信息,其中条件是多个电话号码?

node.js - 如何等待 fs.readFile?

javascript - 使消息返回所有数据库行

javascript - 如何将选择值获取到 Controller 中