首页 > 解决方案 > 如果 forEach 使用 Promise.all 而不是 async/await

问题描述

我正在制作一个不和谐的机器人,使用discord.js它从 API 获取数据并添加或删除与数据关联的消息。

在下面的代码片段中,如果相应的数据在 API 中不再可用,我编写了删除消息的逻辑。

gameEmbeds是一个映射,它包含key作为来自 API 的数据val的标识符和作为不和谐通道中消息的标识符。

  gameEmbeds.forEach(async (val, key, map) => {
  if (map !== undefined && newGames.get(key) === undefined) {
    const message = await channel.fetchMessage(val);
    message.delete()
      .catch((e) => {
        console.error(`${new Date()} `, e);
      });
  }

我必须制作迭代器功能async,因为每个条目都要被一一处理,以使 UI 中的更改看起来更平滑,这违反了 JS 的异步特性。

我想我可以确保发生这种情况,Promise.all这也会使这段代码更快一点,但是,我不知道如何在我的代码中实现它而不破坏东西。我是 node.js 的新手。请帮忙。

编辑:感谢 CF256,我删除了多余的.then()

标签: node.jspromiseasync-awaitdiscord.js

解决方案


我将创建一个新数组来保存所有小承诺,一旦forEach循环完成,我将调用Promise.all小承诺 keeper

const allDeleteJobs = [];
gameEmbeds.forEach(async (val, key, map) => {
  if (map !== undefined && newGames.get(key) === undefined) {
    const message = await channel.fetchMessage(val);
    // Push the new delete job to the array registry
    allDeleteJobs.push(message.delete());
  }
});
(async () => {
  if(allDeleteJobs.length >= 1){
    await Promise.all(allDeleteJobs);
    // Delete all the messages or do other stuff
  }
})()
.catch(error => console.error(error));


推荐阅读