node.js - 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
and混合try/catch
。void
将操作员放在refreshToken()
. 感觉像是在作弊。- 放在
await
前面refreshToken()
。基本上破坏了我的应用程序(在等待令牌过期时暂停应用程序的执行,因此前端的用户无法搜索电影)。
关于如何解决这个问题的任何想法?
另外,有什么建议的资源/主题来研究这个吗?因为我昨天遇到了类似的问题,尽管已经解决了另一个问题,但我仍然无法解决这个问题。干杯 =)
解决方案
推荐阅读
- arduino - Arduino Uno stepper direction
- linux - 将参数传递给 linux shell 以从 git 存储库克隆
- python - 在 python 中使用'for'循环转置矩阵的问题编写代码
- php - 安装插件“致命错误:无法声明类 Stripe\Stripe,因为名称已在使用中”
- javascript - 带有 POST 请求的 Chrome 扩展重定向到本地页面
- python - 如何根据 python 脚本的运行日期发送两个文件名之一?
- python - 使用 CGI 运行烧瓶和 python
- python - 使用 Python 解析 JSON 文件中的字典
- node.js - 如何用字符串中的另一个子字符串替换所有出现的子字符串?
- python - 无法安装 postgres_copy 模块