52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import { ref, watch, onUnmounted, type Ref } from 'vue'
|
|
import { getTaskStatus } from '../api/tasks'
|
|
|
|
export function useTaskPoller(taskIdRef: Ref<string | null>) {
|
|
const status = ref<string>('')
|
|
const isPolling = ref(false)
|
|
const error = ref<string | null>(null)
|
|
const result = ref<any>(null)
|
|
let timer: any = null
|
|
|
|
const start = () => {
|
|
if (!taskIdRef.value) return
|
|
isPolling.value = true
|
|
error.value = null
|
|
status.value = 'PENDING'
|
|
|
|
timer = setInterval(async () => {
|
|
try {
|
|
const res = await getTaskStatus(taskIdRef.value!)
|
|
status.value = res.status
|
|
|
|
if (res.status === 'SUCCESS') {
|
|
result.value = res
|
|
stop()
|
|
} else if (res.status === 'FAILED') {
|
|
error.value = res.error || '任务执行失败'
|
|
stop()
|
|
}
|
|
} catch (e: any) {
|
|
error.value = '网络请求失败,请检查后端状态'
|
|
stop()
|
|
}
|
|
}, 2000)
|
|
}
|
|
|
|
const stop = () => {
|
|
isPolling.value = false
|
|
if (timer) clearInterval(timer)
|
|
}
|
|
|
|
// 监听 Task ID 变化自动开启轮询
|
|
watch(taskIdRef, (newVal) => {
|
|
stop()
|
|
if (newVal) start()
|
|
})
|
|
|
|
// 组件销毁时清理定时器
|
|
onUnmounted(() => stop())
|
|
|
|
return { status, isPolling, error, result, stop }
|
|
}
|