首页 > 解决方案 > TypeScript:如何处理 setTimeout() 中的异步函数?

问题描述

我有以下定时函数来定期从您常用的电影获取 IMDB 克隆应用程序中的外部 API 重新获取凭据:

  // This variable I pass later to Apollo Server, below all this code.
  let tokenToBeUsedLater: string;

  // Fetch credentials and schedule a refetch before they expire
  const fetchAndRefreshToken = async () => {
    try {

      // fetchCredentials() sends an http request to the external API:
      const { access_token, expires_in} = await fetchCredentials() as Credentials;

      tokenToBeUsedLater = access_token;

      // The returned token expires, so the timeout below is meant to recursively
      // loop this function to refetch fresh credentials shortly before expiry.
      // This timeout should not stop the app's execution, so can't await it.
      // Have also tried the following with just setTimeout() and 
      // no `return new Promise()`but it throws a 2nd identical error.
      return new Promise(resolve => setTimeout(() => {
        resolve(fetchAndRefreshToken());
      }, expires_in - 60000));

    } catch (err) { throw new Error(err); }
  };

  fetchAndRefreshToken();  // <-- TypeScript error here

我试过用一千种方式重写它,但无论我做什么,我都会Promises must be handled appropriately or explicitly marked as ignored with the 'void' operator出错。

我可以通过以下方式消除错误:

关于如何解决这个问题的任何想法?

另外,有什么建议的资源/主题来研究这个吗?因为我昨天遇到了类似的问题,尽管已经解决了另一个问题,但我仍然无法解决这个问题。干杯 =)

标签: node.jsasynchronouspromisesettimeoutnode-fetch

解决方案


推荐阅读