如何在继续代码之前捕获错误



我有一个命令,它会向公会中的每个用户发送一条消息。当然,用户有可能关闭DM。我想通过使用.catch来计算这些用户(并向禁用DM的用户数量的频道发送消息(。

我的问题是,.catch块在命令的剩余部分(它向通道发送消息的部分(之后执行自己在.catch块中,我向变量添加1,每次它都会给我错误。在通道消息中,我发送变量。显然,变量将是0,因为它在运行.catch块之前发送消息。

在关闭消息的用户数量为的情况下,如何在.catch块之后发送消息?

这是我的代码:

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()都是异步的。为此,您需要为每个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')

相关内容

最新更新