Skip to content

useAsync

一个强大的异步操作状态管理 Hook,提供统一的异步操作状态管理方案,支持加载状态、错误处理、手动执行等功能。

基础用法

📤 文件上传

立即执行示例

📊 数据统计

📈 正在加载统计数据...

API 参考

参数

参数类型默认值说明
asyncFnAsyncFunction<T, P>-异步函数,支持参数
optionsUseAsyncOptions{}配置选项

UseAsyncOptions

属性类型默认值说明
immediatebooleanfalse是否立即执行异步函数
resetDelaynumber0重置延迟时间(毫秒)
onSuccess(data: T) => void-成功回调函数
onError(error: Error) => void-错误回调函数
onFinally() => void-完成回调函数(无论成功失败)

返回值

useAsync 返回一个数组,包含以下元素:

typescript
const [data, loading, error, execute, reset, status] = useAsync(asyncFn, options);
索引名称类型说明
0dataComputedRef<T | null>异步操作的结果数据
1loadingComputedRef<boolean>是否正在加载
2errorComputedRef<Error | null>错误信息
3executeAsyncExecuteFunction<P>手动执行异步函数
4resetResetFunction重置状态函数
5statusComputedRef<AsyncStatus>当前状态

AsyncStatus

typescript
type AsyncStatus = "idle" | "pending" | "success" | "error";
  • idle - 初始状态
  • pending - 执行中
  • success - 执行成功
  • error - 执行失败

类型定义

typescript
export type AsyncFunction<T, P extends any[] = any[]> = (
  ...args: P
) => Promise<T>;

export type AsyncExecuteFunction<P extends any[] = any[]> = (
  ...args: P
) => Promise<void>;

export type ResetFunction = () => void;

export type UseAsyncOptions {
  immediate?: boolean;
  resetDelay?: number;
  onSuccess?: (data: any) => void;
  onError?: (error: Error) => void;
  onFinally?: () => void;
}

export type UseAsyncReturn<T, P extends any[] = any[]> = [
  ComputedRef<T | null>,
  ComputedRef<boolean>,
  ComputedRef<Error | null>,
  AsyncExecuteFunction<P>,
  ResetFunction,
  ComputedRef<AsyncStatus>,
];

使用场景

  1. 数据提交 - 表单提交、文件上传等
  2. 数据加载 - 页面初始化数据加载
  3. 用户操作 - 删除、更新等需要异步处理的操作
  4. 状态管理 - 统一管理异步操作的各种状态

注意事项

  1. execute 函数支持传递参数给异步函数
  2. 设置 immediate: true 时会在组件挂载时自动执行
  3. reset 函数会清除所有状态,恢复到初始状态
  4. 回调函数在相应的状态变化时触发
  5. 组件卸载时会自动取消正在进行的异步操作

基于 MIT 协议发布