如何解决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
错误。
我可以通过以下方式消除错误:
- 在调用
.then().catch()
时使用refreshToken()
。不理想,因为我不想将它与async
和try/catch
混合。 - 将
void
运算符放在refreshToken()
之前。感觉像是在作弊。 - 将
await
放在refreshToken()
之前。基本上破坏了我的应用程序(在等待令牌到期时暂停应用程序的执行,因此前端的用户无法搜索电影)。
知道如何解决这个问题吗?
此外,是否有任何建议的资源/主题可供研究?因为我有一个 similar issue yesterday 并且尽管已经解决了另一个我仍然无法弄清楚这个。干杯 =)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。