Skip to content

Commit

Permalink
fix: timeoutId compatible for browser-like environments (#16)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
psyirius and antfu committed Feb 21, 2024
1 parent 34ced14 commit 0648a21
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
timeout = DEFAULT_TIMEOUT,
} = options

const rpcPromiseMap = new Map<string, { resolve: (arg: any) => void, reject: (error: any) => void, timeoutId: Parameters<typeof clearTimeout>[0] }>()
const rpcPromiseMap = new Map<string, { resolve: (arg: any) => void, reject: (error: any) => void, timeoutId?: ReturnType<typeof setTimeout> }>()

let _promise: Promise<any> | any

Expand All @@ -185,7 +185,7 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
await _promise
return new Promise((resolve, reject) => {
const id = nanoid()
let timeoutId
let timeoutId: ReturnType<typeof setTimeout> | undefined

if (timeout >= 0) {
timeoutId = setTimeout(() => {
Expand All @@ -198,7 +198,11 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
reject(e)
}
rpcPromiseMap.delete(id)
}, timeout).unref?.()
}, timeout)

// For node.js, `unref` is not available in browser-like environments
if (typeof timeoutId === 'object')
timeoutId = timeoutId.unref?.()
}

rpcPromiseMap.set(id, { resolve, reject, timeoutId })
Expand Down

0 comments on commit 0648a21

Please sign in to comment.