Skip to content

Commit

Permalink
revise implementation to simplify promise executor
Browse files Browse the repository at this point in the history
  • Loading branch information
loucadufault committed Dec 4, 2024
1 parent faa35ef commit 494f579
Showing 1 changed file with 32 additions and 24 deletions.
56 changes: 32 additions & 24 deletions packages/webhid/src/methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,29 +70,37 @@ export async function setupXkeysPanel(browserDevice: HIDDevice): Promise<XKeys>
})

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
try {
await new Promise<void>((resolve, reject) => {
const markRejected = (e: unknown) => {
reject(e)
alreadyRejected = true
}
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))
})
const xkeysStopgapErrorHandler = (e: unknown) => {
if (alreadyRejected) {
console.error(`Xkeys: Error emitted after setup already rejected:`, e)
return
}

markRejected(e)
}

// Handle all error events until the instance is returned
xkeys.on('error', xkeysStopgapErrorHandler)

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

return xkeys
} catch (e) {
await deviceWrap.close()
throw e
}
}

0 comments on commit 494f579

Please sign in to comment.