【问题标题】:Use Promise.all instead of async/await if a forEach如果 forEach 使用 Promise.all 而不是 async/await
【发布时间】:2018-12-01 18:31:00
【问题描述】:

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

在下面的 sn-p 中,我编写了在 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()

【问题讨论】:

  • 使用 async/await 时不要使用 .then 或 .catch。如果 fetchMessage 是一个返回消息的承诺,你可以做 const message = await channel.fetchMessage(val)
  • 谢谢 我想尽可能优化我的代码。但是如何在forEach 上使用Promise.all
  • @CF256 现在怎么样了?
  • 您是否意识到.forEach() 不会等待异步回调。你不是在这里序列化你的操作。所有 async/await 在这里所做的就是让您在 channel.fetchMessage() 完成后调用 message.delete()。你的循环没有序列化。您的所有操作都是并行进行的。
  • 我希望它们同时发生以节省时间。

标签: node.js promise async-await discord.js


【解决方案1】:

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

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));

【讨论】:

  • 如何将函数(message.delete()) 推送到数组中?
  • Array.push(stuff)
  • 但是message.delete() 是一个函数,而不是一个值,对吧?
  • 是的 message.delete() 确实是一个函数,但是你仍然可以将它推入一个数组,它不会破坏你的代码,如果你想以某种方式检索 message.delete() 的返回值,您总是可以从Promise.all 函数中获取值,返回格式将是一个数组,按您之前如何推送值排序
  • 等等,我的函数中仍然没有去掉 async/await
猜你喜欢
  • 2018-12-26
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 2023-03-10
  • 2018-06-27
  • 2022-11-23
相关资源
最近更新 更多