跳至内容

useAsyncQueue

类别
导出大小
511 B
上次更改
上个月

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

演示

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) // current pending task index

console.log(result) // the tasks 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) // current pending task index
console.log(result) // the tasks 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 {
  /**
   * Interrupt tasks when current task fails.
   *
   * @default true
   */
  interrupt?: boolean
  /**
   * Trigger it when the tasks fails.
   *
   */
  onError?: () => void
  /**
   * Trigger it when the tasks ends.
   *
   */
  onFinished?: () => void
  /**
   * A AbortSignal that can be used to abort the task.
   */
  signal?: AbortSignal
}
/**
 * Asynchronous queue task controller.
 *
 * @see https://vueuse.org.cn/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
ethansnow2012
cross-origin
Okoro Redemption
donotloveshampo
Yugang Cao
webfansplz

变更日志

v10.4.0 于 2023年8月25日
22e26 - feat: 在 typescript 中支持无限任务 (#3333)
v10.2.0 于 2023年6月16日
7da7c - feat: 添加 options.signal 参数 (#3033)

在 MIT 许可下发布。