等待事件触发,直到继续执行代码
Await for event to fire until continuing the code
我又回来了。我有一个关于我遇到的 Discord.js 问题的问题。所以,我想检查当同一用户使用命令时用户是否加入了 voiceChannel。然后,当他确实加入语音频道时,我想阻止该听众收听该事件。
好的,我有这个小命令集可以检查用户是否在语音频道中。
if (!message.member.voiceChannel) {
// Request to join voiceChannel.
}
之后,我收到一条消息,上面写着 "Please join a voice channel" 之类的,不重要。然而,重要的是我想听的事件,这与 voiceStateUpdate
类似。我想等到该事件触发(因此当用户加入语音频道时),然后执行其余代码。
await Client.on("voiceStateUpdate", function (Old, member) {
// Do stuff, event got fired.
});
最后,我想知道这是否可行。等待有人加入频道,然后继续其他人。
谢谢。
~Q
正如 bambam 在他的评论中提到的那样,您不能等待回调...事实上,这就是回调的全部要点 - 在完成大型操作时保持主线程 free/running。
我不知道 Discord 库的复杂性,所以可能有 Client.on(voiceStatusUpdate)
函数的 promise 版本……但从 vanilla JS 的角度来看,您可以包装现有代码在承诺中,await
承诺的完成:
await new Promise( (resolve, reject) => {
Client.on("voiceStateUpdate", function (Old, member) {
// Do stuff, event got fired.
// After you've finished doing your stuff here, tell the promise you're finished.
// Then, since the promise has "resolved", the code will continue past the "await"d line
resolve()
});
})
*请注意,您必须使用 async
关键字标记您的父函数,以便在其中使用 await
...但是如果您弄乱 async/await,我想您可能已经熟悉该要求了。
我又回来了。我有一个关于我遇到的 Discord.js 问题的问题。所以,我想检查当同一用户使用命令时用户是否加入了 voiceChannel。然后,当他确实加入语音频道时,我想阻止该听众收听该事件。
好的,我有这个小命令集可以检查用户是否在语音频道中。
if (!message.member.voiceChannel) {
// Request to join voiceChannel.
}
之后,我收到一条消息,上面写着 "Please join a voice channel" 之类的,不重要。然而,重要的是我想听的事件,这与 voiceStateUpdate
类似。我想等到该事件触发(因此当用户加入语音频道时),然后执行其余代码。
await Client.on("voiceStateUpdate", function (Old, member) {
// Do stuff, event got fired.
});
最后,我想知道这是否可行。等待有人加入频道,然后继续其他人。
谢谢。 ~Q
正如 bambam 在他的评论中提到的那样,您不能等待回调...事实上,这就是回调的全部要点 - 在完成大型操作时保持主线程 free/running。
我不知道 Discord 库的复杂性,所以可能有 Client.on(voiceStatusUpdate)
函数的 promise 版本……但从 vanilla JS 的角度来看,您可以包装现有代码在承诺中,await
承诺的完成:
await new Promise( (resolve, reject) => {
Client.on("voiceStateUpdate", function (Old, member) {
// Do stuff, event got fired.
// After you've finished doing your stuff here, tell the promise you're finished.
// Then, since the promise has "resolved", the code will continue past the "await"d line
resolve()
});
})
*请注意,您必须使用 async
关键字标记您的父函数,以便在其中使用 await
...但是如果您弄乱 async/await,我想您可能已经熟悉该要求了。