Skip to content

Commit

Permalink
handle error events on xkeys that can be emitted during the init proc…
Browse files Browse the repository at this point in the history
…ess before the instance is exposed for listener registration
  • Loading branch information
loucadufault committed Dec 3, 2024
1 parent 723cf1b commit 913403b
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions packages/webhid/src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,28 @@ export async function setupXkeysPanel(browserDevice: HIDDevice): Promise<XKeys>
})
})

// Wait for the device to initialize:
try {
await xkeys.init()

return xkeys
} catch (e) {
await deviceWrap.close()
throw e
}
let alreadyRejected = false
return new Promise((resolve, reject) => {
const xkeysStopgapErrorHandler = (e: unknown) => {
if (alreadyRejected) {
console.error(`Xkeys: Error emitted after setup already rejected:`, e)
return
}
deviceWrap.close()
.then(() => reject())
.catch(reject)
.finally(() => (alreadyRejected = true))
}
// Handle all error events until the instance is returned
xkeys.on('error', xkeysStopgapErrorHandler)

// Wait for the device to initialize:
xkeys.init()
.then(() => {
resolve(xkeys)
xkeys.removeListener('error', xkeysStopgapErrorHandler)
})
.catch(reject)
.finally(() => (alreadyRejected = true))
})
}

0 comments on commit 913403b

Please sign in to comment.