useAsync
一个强大的异步操作状态管理 Hook,提供统一的异步操作状态管理方案,支持加载状态、错误处理、手动执行等功能。
基础用法
📤 文件上传
立即执行示例
📊 数据统计
📈 正在加载统计数据...
API 参考
参数
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
asyncFn | AsyncFunction<T, P> | - | 异步函数,支持参数 |
options | UseAsyncOptions | {} | 配置选项 |
UseAsyncOptions
属性 | 类型 | 默认值 | 说明 |
---|---|---|---|
immediate | boolean | false | 是否立即执行异步函数 |
resetDelay | number | 0 | 重置延迟时间(毫秒) |
onSuccess | (data: T) => void | - | 成功回调函数 |
onError | (error: Error) => void | - | 错误回调函数 |
onFinally | () => void | - | 完成回调函数(无论成功失败) |
返回值
useAsync
返回一个数组,包含以下元素:
typescript
const [data, loading, error, execute, reset, status] = useAsync(asyncFn, options);
索引 | 名称 | 类型 | 说明 |
---|---|---|---|
0 | data | ComputedRef<T | null> | 异步操作的结果数据 |
1 | loading | ComputedRef<boolean> | 是否正在加载 |
2 | error | ComputedRef<Error | null> | 错误信息 |
3 | execute | AsyncExecuteFunction<P> | 手动执行异步函数 |
4 | reset | ResetFunction | 重置状态函数 |
5 | status | ComputedRef<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>,
];
使用场景
- 数据提交 - 表单提交、文件上传等
- 数据加载 - 页面初始化数据加载
- 用户操作 - 删除、更新等需要异步处理的操作
- 状态管理 - 统一管理异步操作的各种状态
注意事项
execute
函数支持传递参数给异步函数- 设置
immediate: true
时会在组件挂载时自动执行 reset
函数会清除所有状态,恢复到初始状态- 回调函数在相应的状态变化时触发
- 组件卸载时会自动取消正在进行的异步操作