【问题标题】:TypeScript: type for returning an async function call inside a setTimeout()?TypeScript:用于在 setTimeout() 中返回异步函数调用的类型?
【发布时间】:2021-07-06 21:21:09
【问题描述】:

我有一个获取外部 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 函数中强输入 return,我不断收到 Promise returned in function argument where a void return was expected. 错误。我尝试了函数retryFetchCredentials 的几种返回类型,但均无济于事。

关于如何解决这个问题的任何线索?

【问题讨论】:

  • setTimeout 的回调返回与从.then 回调返回相同。您可能需要将超时包装在 new Promise 中,以便您可以 resolve 值。
  • 好的,这个,连同下面拉斯的回答,成功了,谢谢!!

标签: node.js typescript asynchronous node-fetch


【解决方案1】:

只需从 setTimeout 内部的函数中删除 return 即可使错误消失,而不会影响其余代码的行为。

附带说明一下,为了保持一致性,您不应将async/await.then 混合使用。如果你尽可能使用async/await,你的代码将会增加它的可读性。

【讨论】:

  • 我按照你说的重写了它,它摆脱了错误,谢谢=)。我使用then 的原因是因为在我通常的try-catch 中,我不断收到错误Promises must be handled appropriately or explicitly marked as ignored with the void operator,而且我还没有想出在没有then() 或使用@987654331 的情况下摆脱它的方法@运算符。
  • @HigoChumbo 我自己没有遇到过这个错误。您可能应该在这里提出另一个关于如何修复它的问题,因为它不正常并且您的代码/项目可能有问题。还有一点小提醒,如果对你有帮助,别忘了采纳答案,这样以后也可以帮助其他人和你有同样问题的人。
猜你喜欢
  • 1970-01-01
  • 2022-12-21
  • 2018-12-12
  • 2019-07-09
  • 2020-12-07
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多