如果 forEach 使用 Promise.all 而不是 async/await
Use Promise.all instead of async/await if a forEach
我正在使用 discord.js
制作一个 discord 机器人,它从 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
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));
我正在使用 discord.js
制作一个 discord 机器人,它从 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
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));