useAsyncQueue
依次执行每个异步任务,并将当前任务的结果传递给下一个任务
Demo
activeIndex: -1
result: [
{
"state": "pending",
"data": null
},
{
"state": "pending",
"data": null
}
]
用法
ts
import { useAsyncQueue } from '@vueuse/core'
function p1() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(1000)
}, 10)
})
}
function p2(result: number) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(1000 + result)
}, 20)
})
}
const { activeIndex, result } = useAsyncQueue([p1, p2])
console.log(activeIndex.value) // 当前待处理任务的索引
console.log(result) // 任务结果
js
import { useAsyncQueue } from '@vueuse/core'
function p1() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(1000)
}, 10)
})
}
function p2(result) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(1000 + result)
}, 20)
})
}
const { activeIndex, result } = useAsyncQueue([p1, p2])
console.log(activeIndex.value) // 当前待处理任务的索引
console.log(result) // 任务结果
类型声明
typescript
export type UseAsyncQueueTask<T> = (...args: any[]) => T | Promise<T>
type MapQueueTask<T extends any[]> = {
[K in keyof T]: UseAsyncQueueTask<T[K]>
}
export interface UseAsyncQueueResult<T> {
state: "aborted" | "fulfilled" | "pending" | "rejected"
data: T | null
}
export interface UseAsyncQueueReturn<T> {
activeIndex: Ref<number>
result: T
}
export interface UseAsyncQueueOptions {
/**
* 当当前任务失败时,是否中断任务队列。
*
* @default true
*/
interrupt?: boolean
/**
* 当任务失败时触发。
*
*/
onError?: () => void
/**
* 当任务结束时触发。
*
*/
onFinished?: () => void
/**
* 可用于中止任务的 AbortSignal。
*/
signal?: AbortSignal
}
/**
* 异步任务队列控制器
*
* @see https://vueuse.org/useAsyncQueue
* @param tasks
* @param options
*/
export declare function useAsyncQueue<T extends any[], S = MapQueueTask<T>>(
tasks: S & Array<UseAsyncQueueTask<any>>,
options?: UseAsyncQueueOptions,
): UseAsyncQueueReturn<{
[P in keyof T]: UseAsyncQueueResult<T[P]>
}>
Source
贡献者
Anthony Fu
丶远方
Anthony Fu
ethansnow2012
cross-origin
Okoro Redemption
donotloveshampo
Yugang Cao
webfansplz