Commit 8a3af690 authored by hewenhao's avatar hewenhao

feat(native-bridge): 增加invokeNativeMethod超时控制功能

为invokeNativeMethod函数添加可选的timeout参数,默认值为10秒, 允许调用者自定义超时时间。当timeout大于0时启用超时机制, 小于等于0时禁用超时。同时修复了定时器清理逻辑, 确保在回调执行时正确清除定时器。
parent 2792a20a
......@@ -87,20 +87,25 @@ export { useNativeBridge }
const INVOKE_NATIVE_METHOD_TIMEOUT = 10000
function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }): Promise<T> {
function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }, timeout = INVOKE_NATIVE_METHOD_TIMEOUT): Promise<T> {
return new Promise((resolve, reject) => {
const callbackName = `${arg.type}_callback_${Math.random()}`.replace(/\./, '')
const timer = setTimeout(() => {
reject(new Error(`invoke ${arg.type} timeout`))
eventBus.off(GEEK_NATIVE_NAME, onCallback)
}, INVOKE_NATIVE_METHOD_TIMEOUT)
let timer: ReturnType<typeof setTimeout> | null = null
// 如果 timeout 大于 0,则设置一个定时器,如果超时则拒绝请求
if (timeout > 0) {
timer = setTimeout(() => {
reject(new Error(`invoke ${arg.type} timeout`))
eventBus.off(GEEK_NATIVE_NAME, onCallback)
}, timeout)
}
eventBus.on(GEEK_NATIVE_NAME, onCallback)
function onCallback (params?: NativeInvokeFuncParams) {
if (params?.method === callbackName) {
clearTimeout(timer)
if (timer) {
clearTimeout(timer)
}
if (params.error) {
reject(new Error(params.error))
} else {
......@@ -165,5 +170,5 @@ export interface WechatOpenBusinessViewResp extends WechatBaseResp {
}
export function requestMerchantTransfer (params: RequestMerchantTransferParams) {
return invokeNativeMethod<WechatOpenBusinessViewResp, RequestMerchantTransferParams>({ type: 'requestMerchantTransfer', data: params })
return invokeNativeMethod<WechatOpenBusinessViewResp, RequestMerchantTransferParams>({ type: 'requestMerchantTransfer', data: params }, -1)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment