From bc6dcdde93da18c7975fba7f8b235ce50837cdec Mon Sep 17 00:00:00 2001 From: liaochunxin Date: Tue, 23 Sep 2025 15:36:33 +0800 Subject: [PATCH] =?UTF-8?q?fix(api):=20=E4=BF=AE=E6=94=B9=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=94=AF=E6=8C=81=E5=BC=82=E6=AD=A5=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E5=92=8C=E6=99=AE=E9=80=9A=E5=87=BD=E6=95=B0=EF=BC=8C=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E8=BF=94=E5=9B=9EPromise=EF=BC=8C=E5=A2=9E=E5=BC=BA?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/foo.ts | 4 ++-- src/hooks/useRequest.ts | 32 ++++++++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/api/foo.ts b/src/api/foo.ts index cfa39a5..a500002 100644 --- a/src/api/foo.ts +++ b/src/api/foo.ts @@ -21,8 +21,8 @@ export interface IFooItem { } /** GET 请求 */ -export function getFooAPI(name: string) { - return http.get('/foo', { name }) +export async function getFooAPI(name: string) { + return await http.get('/foo', { name }) } /** GET 请求;支持 传递 header 的范例 */ export function getFooAPI2(name: string) { diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 7aa7bc6..7eae39e 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -26,7 +26,7 @@ interface IUseRequestReturn { * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。 */ export default function useRequest( - func: (args?: P) => HttpRequestResult, + func: (args?: P) => Promise | Promise> | HttpRequestResult | T, options: IUseRequestOptions = { immediate: false }, ): IUseRequestReturn { const loading = ref(false) @@ -36,12 +36,36 @@ export default function useRequest( const run = async (args?: P) => { loading.value = true - const { promise, requestTask: task } = func(args) - requestTask = task // Store the requestTask + error.value = false // Move error reset to the beginning + let promise: Promise + const result = func(args) + + if (result instanceof Promise) { + // If func returns a Promise + promise = result.then((res) => { + if (res && typeof (res as HttpRequestResult).promise === 'object' && typeof (res as HttpRequestResult).requestTask === 'object') { + // If the resolved value is HttpRequestResult + const { promise: p, requestTask: task } = res as HttpRequestResult + requestTask = task + return p + } + return res as T | undefined + }) as Promise // Cast to ensure correct type + } + else if (result && typeof (result as HttpRequestResult).promise === 'object' && typeof (result as HttpRequestResult).requestTask === 'object') { + // If func returns HttpRequestResult directly + const { promise: p, requestTask: task } = result as HttpRequestResult + requestTask = task + promise = p + } + else { + // If func returns T directly + promise = Promise.resolve(result as T | undefined) + } + return promise .then((res) => { data.value = res - error.value = false return data.value }) .catch((err) => {