TypeScript:用于在 setTimeout() 中返回异步函数调用的类型?

问题描述

我有一个为外部 API 获取凭据的函数(过于简化):

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,您的代码将提高其可读性。