NodeJS SetInterval 与 Async/Await [英] NodeJS SetInterval with Async/Await
问题描述
我使用以下代码和 websocket 从数据库中抓取数据并返回给用户.它返回聊天消息、用户状态和其他内容.代码按预期工作(在测试中),但我有几个问题.
I'm using the following code with a websocket to scrape data from a DB and return to users. It returns chat messages, users status and other things. The code works as expected (in testing) but I have a couple of questions.
setInterval(async () => {
if (connectedUserIDs.length > 0) {
logger.info("short loop...")
await eventsHelper.extractEvents(db, connectedUserIDs, connectedSockets, ws)
}
}, 5000)
问题 1. SetInterval 是否会等待await"?还是每 5 秒触发一次?我假设它会每 5 秒触发一次.
Question 1. Will the SetInterval wait for the the "await" or will it just fire every 5 seconds? I assume it will fire every 5 seconds regardless.
如果是这样.
问题 2. 有没有办法重复上述任务,但确保仅在前一次运行完成且最短时间为 5 秒时才重新运行?我想避免同时运行多个查询的情况.也许每次都可以取消并重新启动 setInterval...
Question 2. Is there a way to repeat a task like above but ensure it only re-runs if the previous run as completed with a minimum time of 5 seconds? I want to avoid a situation where I get multiple queries running at the same time. Maybe the setInterval could be cancelled and restarted each time...
谢谢亚当
推荐答案
问题 1. SetInterval 是否会等待await"?还是每 5 秒触发一次?我假设它会每 5 秒触发一次.
Question 1. Will the SetInterval wait for the the "await" or will it just fire every 5 seconds? I assume it will fire every 5 seconds regardless.
是的,它会天真地每 5 秒重新运行一次
Yes it will naively re-run every 5s
问题 2. 有没有办法重复上述任务,但确保仅在前一次运行至少 5 秒内完成时才重新运行
Question 2. Is there a way to repeat a task like above but ensure it only re-runs if the previous run as completed with a minimum time of 5 seconds
防止冲突的最简单方法是在等待之后设置下一次运行:
Easiest way to prevent collisions is to set the next run after the await:
let timeoutId;
const extractEvents = async () => {
if (connectedUserIDs.length > 0) {
logger.info("short loop...");
await eventsHelper.extractEvents(db, connectedUserIDs, connectedSockets, ws);
}
timeoutId = setTimeout(extractEvents, 5000);
};
timeoutId = setTimeout(extractEvents, 5000);
存储 timeoutId 以便稍后清除
Storing timeoutId so you can clear it later
这篇关于NodeJS SetInterval 与 Async/Await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!