Skip to content

useAsyncQueue

类别
导出体积
505 B
上次更改
7 months ago

依次执行每个异步任务,并将当前任务的结果传递给下一个任务

示例

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) // 任务结果

类型声明

ts
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
:
ShallowRef
<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
]>
}>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
IlyaL
Robin
ethansnow2012
cross-origin
Okoro Redemption
donotloveshampo
Yugang Cao
webfansplz

更新日志

0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
22e26 - feat: support in infinite tasks in typescript (#3333)
7da7c - feat: add options.signal parameter (#3033)