【发布时间】: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