diff --git a/src/index.ts b/src/index.ts index 591c843..f8274c9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -155,7 +155,7 @@ export function createBirpc( timeout = DEFAULT_TIMEOUT, } = options - const rpcPromiseMap = new Map() + const rpcPromiseMap = new Map[0] }>() let _promise: Promise | any @@ -176,14 +176,17 @@ export function createBirpc( await _promise return new Promise((resolve, reject) => { const id = nanoid() - rpcPromiseMap.set(id, { resolve, reject }) - post(serialize({ m: method, a: args, i: id, t: 'q' })) + let timeoutId + if (timeout >= 0) { - setTimeout(() => { + timeoutId = setTimeout(() => { reject(new Error(`[birpc] timeout on calling "${method}"`)) rpcPromiseMap.delete(id) - }, timeout) + }, timeout).unref?.() } + + rpcPromiseMap.set(id, { resolve, reject, timeoutId }) + post(serialize({ m: method, a: args, i: id, t: 'q' })) }) } sendCall.asEvent = sendEvent @@ -222,6 +225,8 @@ export function createBirpc( const { i: ack, r: result, e: error } = msg const promise = rpcPromiseMap.get(ack) if (promise) { + clearTimeout(promise.timeoutId) + if (error) promise.reject(error) else