hooks useRequest不打算在轮训失败上限后增加一个onOver吗?

9ceoxa92  于 2022-10-25  发布在  其他
关注(0)|答案(6)|浏览(166)

需求:轮训10次,成功 cancel 取消轮训,失败 pollingErrorRetryCount 上限轮训次数,需要捕获失败并结束轮训发送通知。

目前只能解决 pollingErrorRetryCount 上限结束轮训,如果要在最后一次捕获通知就需要考虑额外的办法。
这是我目前的解决办法,演示链接:
https://codesandbox.io/s/du-qu-yong-hu-ming-cheng-forked-cxhp4k?file=/App.tsx:403-425

很不好,我是通过 onError ,将参数轮训次数递增,达到上限次数捕获错误,这样就要给请求方法增加一个额外参数

建议增加一个类似 onOver 的方法,在最后一次失败轮训的时候能够调用这个方法,类似 onFinally

n8ghc7c1

n8ghc7c11#

感觉可以增加一个钩子函数。你们觉得呢 cc @brickspert@crazylxr

lhcgjxsq

lhcgjxsq2#

我觉得可以先不加

6g8kf2rb

6g8kf2rb3#

我觉得可以先不加

@hchlq@crazylxr 抱歉,我提的建议有个小失误,能否给现有的方法 onSuccessonErroronFinally 增加一个当前请求次数的参数,而不是增加一个回调方法,因为我在 onSuccess 中也需要用到请求计数,例如

(data: TData, params: TParams, count: number) => void

或者是将 TParams 对象改为对象类型返回回来,类似:

{
  params: TParams,
  count: number,
}

其中 count 表示累计轮训的次数

vsaztqbk

vsaztqbk4#

我示范一个项目用到的轮训,大概就明白现在有多麻烦了。我们有这么一个请求,提交操作后,异步轮训获取状态,超过10次没有返回完成状态,就报告异常。如下:

const showNotification = useCallback((config: ArgsProps) => {
        setError(config.type === 'error' ? message : '');
        notification.open({
            ...config,
            key: 'taskNotification',
            placement: 'bottomRight',
        });
    }, [notification, setError]);

    const { cancel, run } = useRequest(getJobInfo, {
        manual: true,
        pollingInterval: 500,
        pollingWhenHidden: false,
        pollingErrorRetryCount: 10,
        onError: (error, params) => {
            if (params[1]++ >= 10) return showNotification({
                description: '请稍后重试或联系技术解决',
                type: 'error',
                message: error.message,
                duration: 10,
            });
        },
        onSuccess: (data, params) => {
            if (data.type !== 'pass_success') {
                if (params[1]++ >= 10) {
                    cancel();
                    showNotification({
                        description: '计划审核队列操作超时,请联系技术解决',
                        type: 'error',
                        message: error.message,
                        duration: 10,
                    });
                }
                return;
            }
            cancel();
            showNotification({
                description: '将按照计划时间分配,并统计数据',
                message: '已成功完成计划审核',
                type: 'success',
            });
        },
    });

其中 run 的时候除了要提供请求参数以外,还有增加一个初始参数 0

run(id, 0);
px9o7tmv

px9o7tmv5#

const { pollingCount } = useRequest(getJobInfo)

如果这样返回是不是也可以满足你的需求?

pengsaosao

pengsaosao6#

之前也有 issue 说需要 是否正在轮询这样的状态,可以看下这个 issue ,所以我在想要不返回值里就增加一个轮询相关的对象。把轮询的状态和轮询的次数都返回回来,api 大概像这样。

const { polling } = useRequest()

polling 的定义像这样

属性描述类型
pollingCouter轮询次数number
isPolling是否处于轮询中boolean

相关问题