node.js - 如果 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()
解决方案
我将创建一个新数组来保存所有小承诺,一旦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));
推荐阅读
- c - Structs and arrays challenge in C
- math - 全栈工程师需要多少数学/物理知识?
- powershell - 在 helm install 中执行命令
- sql - 如何在 SQL 中创建查询以获取以前的日期?
- python - 在搜索大量字符串时,如何加快电子邮件查找正则表达式的速度?
- node.js - 更新文档时如何捕捉猫鼬错误
- scala - 生成身份验证令牌并在 Gatling 的整个会话中使用它
- javascript - 在 Jest 中模拟 requestAnimationFrame
- html - 如何更改过渡“outro”?(CSS 变换)
- python - Python OpenPyxl:从按列排列的数据创建折线图