【发布时间】:2021-02-23 04:44:53
【问题描述】:
我遇到了两个异步函数的问题。它们旨在从 API 顺序获取登录链接,但有时 Web 服务尚未准备好,因为它依赖于物理设备(可以重置),有时初始渲染会在服务启动之前发生。
因此,如果未填充 authConfigURL 或 loginURL,则间隔每 2 秒运行两个异步函数,这不可能是最佳的,至少在当前状态下不是。
最初我有一个 useEffect() 和这两个函数并调用它们,将 loginURL 和 authConfigURL 传递给依赖数组。如果未填充 URL,我无法确定以特定时间间隔运行请求的正确方法。
如果不满足条件或请求的响应为空,是否有更好的方法来处理调用函数?
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
savedCallback.current();
}
let id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
}
useInterval(() => {
if (!authConfigURL || !loginURL) {
setIsWaiting(true);
fetchRootResources();
fetchAuthenticationConfig();
}
}, 2000);
async function fetchRootResources() {
const rootURL = "/admin/api/rest/";
try {
const response = await fetch(rootURL, {
method: "GET",
headers: { Accept: "blah"},
});
if (!response.ok) {
console.error("Handle response codes", response);
setErrorMessage("Error fetching Root REST API Resources");
}
// if the response contains no data this will error out
const data = await response.json();
// set rootResources here
setRootResources({
time: data.links.time,
// 10 or so other links
});
// this URL is needed in the next async function
setAuthConfigURL(data.links.auth_config);
} catch (error) {
console.log("Error fetching root resources", error);
}
}
async function fetchAuthenticationConfig() {
// authConfigURL seems to be empty on initial render
console.log("fetching authConfig with url: ", authConfigURL);
try {
const response = await fetch(authConfigURL, {
method: "GET",
headers: { Accept: "blah" },
});
if (!response.ok) {
console.error("Handle response codes", response);
}
const data = await response.json();
console.log(data);
setLoginURL(data.data.links.login);
} catch (error) {
console.log("Error fetching auth config", error.message);
}
}
【问题讨论】:
-
为什么不等待
fetchRootResources完成就调用fetchAuthenticationConfig?这将导致fetchAuthenticationConfig始终使用在前一个间隔中获得的authConfigURL。听起来,如果失败的请求在 2 秒(或更多)秒后超时)重试失败的请求可能比敲击 API 直到获得两个成功的请求更好。 -
所以从区间中删除
fetchAuthenticationConfig()并从fetchRootResources()内部调用它是response.status === 200? -
可能或
fetchRootResources().then(fetchAuthenticationConfig).catch( ... handle errors or retry ...)。回想一下async函数返回一个承诺。恕我直言,使用间隔计时器可能不是一个好的选择。 -
您介意用
.then()举例回答吗? -
为了方便起见,我最终将
fetch调用放在同一个函数中。但是我确实使用了.then子句将处理数据与获取数据分开。请参阅我的答案示例。
标签: javascript reactjs