问题描述
const fetchCredentials= async () => {
return await fetch(/* url and params */);
};
const retryFetchCredentials = (initialDelay = 250): Promise<Credentials | void> => {
return fetchCredentials().then(async res => {
if (res.ok) {
const parsedResponse = await res.json() as Credentials ;
return parsedResponse;
}
else {
// The issue is with this timeout/return:
setTimeout(() => {
return retryFetchCredentials (initialDelay * 2);
},initialDelay);
}
});
};
我的问题是我不知道如何在 setTimeOut 函数中强类型返回,我不断收到 Promise returned in function argument where a void return was expected.
错误。我为函数retryFetchCredentials
尝试了几种返回类型,但都无济于事。
有关如何解决此问题的任何线索?
解决方法
只需从 return
内的函数中删除 setTimeout
即可使错误消失,而不会影响其余代码的行为。
作为旁注,为了保持一致性,您不应将 async
/await
与 .then
混合使用。如果您尽可能使用 async
/await
,您的代码将提高其可读性。