VUE接口任务轮询查询任务封装hooks
usepolling.ts
import { ref } from 'vue'interface Options {time?: numbertotalTime?: numbercount?: numbercallback?(): void }export default function usePolling<T extends () => Promise<any>>(fun: T, options?: Options) {const result = ref(null)const error = ref(null)const {time = 2000,totalTime,count,callback = () => false} = options || ({} as Options)let timer: any = nulllet endTime: number | null = nulllet totalCount = 0const run = () => {if (endTime && endTime <= Date.now()) {end()callback()return}if (count && totalCount >= count) {end()callback()return}totalCount++timer = setTimeout(() => {fun().then((res) => {result.value = resrun()}).catch((err) => {error.value = err})}, time)}const start = () => {endTime = totalTime ? Date.now() + totalTime : nullrun()}const end = () => {setTimeout(() => {clearTimeout(timer)timer = nullendTime = nulltotalCount = 0}, 0)}return {start,end,error,result} }
使用hook
//test.vue import usePolling from '@/hooks/usePolling'; let pollingStart: () => void; let pollingEnd: () => void;/**getTaskProgress方法是需要轮询的方法*/ const { start, end } = usePolling(getTaskProgress, {time: 1000 * 5, });pollingStart = start; pollingEnd = end;/** 查询任务进度 */ const getTaskProgress = () => { //成功状态,结束轮询pollingEnd(); };const beganTask = ()=>{pollingStart(); }