fix(apis/websocket): fix forever stuck Promise

This commit is contained in:
PalmDevs
2024-01-17 22:37:11 +07:00
parent a6907b16c4
commit 168f40def6

View File

@@ -68,8 +68,8 @@ export default class Client {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
try { try {
this.#throwIfDisconnected('Cannot send packet to client that has already disconnected') this.#throwIfDisconnected('Cannot send packet to client that has already disconnected')
this.#socket.send(serializePacket(packet))
this.#socket.send(serializePacket(packet), err => (err ? reject(err) : resolve())) resolve()
} catch (e) { } catch (e) {
reject(e) reject(e)
} }
@@ -91,11 +91,13 @@ export default class Client {
forceDisconnect(reason: DisconnectReason = DisconnectReason.Generic) { forceDisconnect(reason: DisconnectReason = DisconnectReason.Generic) {
if (this.disconnected !== false) return if (this.disconnected !== false) return
if (this.#hbTimeout) clearTimeout(this.#hbTimeout) // It's so weird because if I moved this down a few lines
this.#socket.terminate() // it would just fire the disconnect event twice because of a race condition
this.ready = false
this.disconnected = reason this.disconnected = reason
this.ready = false
if (this.#hbTimeout) clearTimeout(this.#hbTimeout)
this.#socket.close()
this.#emitter.emit('disconnect', reason) this.#emitter.emit('disconnect', reason)
} }
@@ -111,6 +113,7 @@ export default class Client {
#listen() { #listen() {
this.#socket.on('message', data => { this.#socket.on('message', data => {
this.#emitter.emit('message', data)
try { try {
const rawPacket = deserializePacket(this._toBuffer(data)) const rawPacket = deserializePacket(this._toBuffer(data))
if (!isClientPacket(rawPacket)) throw null if (!isClientPacket(rawPacket)) throw null
@@ -192,4 +195,5 @@ export type ClientEventHandlers = {
ready: () => Promise<unknown> | unknown ready: () => Promise<unknown> | unknown
packet: (packet: ClientPacketObject<ClientOperation>) => Promise<unknown> | unknown packet: (packet: ClientPacketObject<ClientOperation>) => Promise<unknown> | unknown
disconnect: (reason: DisconnectReason) => Promise<unknown> | unknown disconnect: (reason: DisconnectReason) => Promise<unknown> | unknown
message: (data: RawData) => Promise<unknown> | unknown
} }