Smally
Smally

Reputation: 1684

Await for event to fire until continuing the code

I'm back again, again. I had a question about a Discord.js problem I've had. So, I'd like to check if a user joined a voiceChannel when the same user used a command. Then when he did join a voice-channel, I'd like to stop that listener on listening to that event.

Ok so, I have this little command set that checks whether the user is in a voice channel or not.

if (!message.member.voiceChannel) {
    // Request to join voiceChannel.
}

After that, I have a message sent that says "Please join a voice channel" or whatever, not important. What is important, however, is the event I'd like to listen to, which is something along the lines of voiceStateUpdate. I'd like to await until that event fired (so when the user joined a voice channel), then execute the rest of the code after that.

await Client.on("voiceStateUpdate", function (Old, member) {
    // Do stuff, event got fired.
});

Lastly, I'd like to know whether this is correctly possible or not. Awaiting​ for somebody to join a channel, then carrying on with the rest.

Thank you. ~Q

Upvotes: 1

Views: 661

Answers (1)

JeremyW
JeremyW

Reputation: 5272

As bambam mentioned in his comment, you can't await a callback... In fact, that's the whole point of a callback - to keep the main thread free/running while a large action is completed.

I don't know the intricacies of the Discord library, so there might be a promise-version of the Client.on(voiceStatusUpdate) function... but just from a vanilla JS perspective, you could wrap your existing code in a promise, and await the completion of the promise:

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()
    });
})

*Note that you'll have to mark your parent function with the async keyword in order to use await inside of it... but if you're messing with async/await, I imagine you're probably already familiar with that requirement.

Upvotes: 1

Related Questions