【问题标题】:Using async await for API call via custom hook通过自定义钩子使用异步等待进行 API 调用
【发布时间】:2022-01-23 19:06:28
【问题描述】:

我有一个自定义的钩子函数如下;

export default function useApiCall() {
const fetchingData = async (url, reqData, reqType) => {
    try {
        var statObj = {         
        };
        var reqopts = {
            credentials: 'same-origin'
        }
        if (reqType === 'POST') {
            reqopts.headers = {};
            reqopts.headers['Accept'] = 'application/json';
            reqopts.headers['Content-Type'] = 'application/json;charset=utf-8';
            reqopts.method = 'POST';
            reqopts.body = JSON.stringify(reqData);
        }
        const response = await fetch(url, reqopts);
        if (!response.ok) {
            throw response;
        }
        statObj.status = "success";
        const json = await response.json();
        return [json, statObj];
    } catch (error) {
        statObj.status = "error";
        if (error && error.status) {
            switch (error.status) {
                default:
                    statObj.errorMessage = "System error occured";
                    console.error("System error occured : " + error.status);
            }
        }
        return [null, statObj];
    }

}
return fetchingData;
}

现在,我使用如下函数

const fetchFn = useApiCall();
const getData = async () => {
    const [response, statObj] = await fetchFn(url, data, 'POST');
    console.log(response);
}

所以,我在这两个地方都使用了 await 关键字...我正在调用的地方以及实际进行调用的地方。

上面的代码看起来不错吗?

【问题讨论】:

  • Does the above code seem fine ? 我没有发现任何问题。您遇到什么问题了吗?
  • 是的,似乎某些 API 调用在第 3 次、第 4 次调用后显示延迟......所以,我看到请求本身在 Chrome 网络选项卡中启动后延迟...不确定是什么原因造成的?

标签: javascript reactjs async-await react-hooks


【解决方案1】:

由于您的自定义挂钩是 async,它返回一个新的 Promise,因此您必须使用 await 关键字来解决该 Promise:

const myFunc = async () => {
  return 1;
}

const test2 = myFunc(); // Promise {}
const test3 = await myFunc(); // 1

您可以改进您的功能:

  1. error && error.status 可以是 error?.status(可选 链接);

  2. 我相信你不需要 switch 部分,因为你 只要有default 选项。

希望对你有帮助=]

【讨论】:

  • 实际上对 useApiCall 的调用会返回一个函数,然后我稍后会调用该函数以进行实际的 API 调用......所以,它不完全是一个钩子,而更像是一个返回函数的实用程序...... ..
  • function useApiCall(): (url: any, reqData: any, reqType: any) => Promise<any[]> 这是您的 useApiCall 函数的签名。返回类型是任意数组的 Promise,看到了吗?
  • 不确定我的理解是否有一些混淆......但我看到 useApiCall 返回的是 fetchingData (这是一个普通的 JS 函数)......这不正确吗?
  • 是的,它返回一个函数本身具有 Promise<any[]> 返回类型,因此 fetchFn 扩展了该返回,因此您需要使用 await 关键字来解析该 Promise。确实有点乱哈哈哈
  • 那么,在我的实际调用代码中,是不是不能去掉 await 关键字?即 const [response, statObj] = await fetchFn(url, data, 'POST')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 2019-01-21
  • 2018-03-31
  • 2019-02-10
  • 2019-07-29
相关资源
最近更新 更多