我有一个命令可以向公会中的每个用户发送一条消息。当然,用户可能会关闭 DM。我想通过使用 .catch
来计算这些用户(并向 channel 发送一条消息,其中包含禁用它的用户数量)。
我的问题是,.catch block 在命令的其余部分之后 执行自身(向 channel 发送消息的部分)
在 .catch
block 中,我将 1 添加到一个变量,每次它都会给我错误。
在 channel 消息中,我发送了变量。显然,该变量将为 0,因为它会在运行 .catch
block 之前发送消息。
如何在.catch
block 后发送消息以及关闭它的用户数量?
这是我的代码:
var text = args.join(' ')
message.guild.members.forEach(member => {
member.send(text).catch(() => {
console.log("Can't send DM to this user!")
faultyusers++
});
});
console.log(faultyusers);
message.channel.send("Successfully sent message to all members in the server. (Warning: **" + faultyusers + "** users might have not received the message because of their settings.)")
(当我运行此程序时,faultyusers 始终为 0。)
最佳答案
每个 member.send()
都是异步的。所以为此你需要创建一个 Promise对于每个 member.send()
调用。之后,你运行所有的 promise ,当它们全部解决时,你会得到一组结果,你可以从中计算没有收到消息的用户数量
// this function returns promise that will
// resolve with { success: true } or { success: false }
// depending on whether or not the user received the message (member.send() failed)
const sendMessageAndGetResult = (text, member) =>
member
.send(text)
.then(() => ({ success: true }))
.catch(() => ({ success: false }))
const sendMessages = async (text) => {
// create one such promise for each user in guild
const promises = message.guild.members.map(member => sendMessageAndGetResult(text, member))
// wait until all promises are resolved
// allResults will be an looking like this [{ success: true }, { success: false }, ...]
const allResults = await Promise.all(promises)
// count users that did not receive message
const faultyUsersCount = allResults.filter(result => !result.success).length
console.log(faultyUsersCount)
message.channel.send("Successfully sent message to all members in the server. (Warning: **" + faultyUsersCount + "** users might have not received the message because of their settings.)")
}
// usage
sendMessages('hello')
关于javascript - 如何在继续代码之前捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58571907/