-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseAsyncTask.ts
More file actions
38 lines (32 loc) · 834 Bytes
/
useAsyncTask.ts
File metadata and controls
38 lines (32 loc) · 834 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { ref } from 'vue'
import { useEnhancedToast } from '@/shared/composables/useEnhancedToast'
export function useAsyncTask(minDelay = 400) {
const isLoading = ref(false)
const { showError } = useEnhancedToast()
async function run<T>(
task: () => Promise<T>,
onSuccess?: (result: T) => void
): Promise<T | null> {
isLoading.value = true
const start = Date.now()
try {
const result = await task()
onSuccess?.(result)
const elapsed = Date.now() - start
const remaining = minDelay - elapsed
if (remaining > 0) {
await new Promise(resolve => setTimeout(resolve, remaining))
}
return result
} catch (error) {
showError(error)
return null
} finally {
isLoading.value = false
}
}
return {
isLoading,
run,
}
}