[英]How to “queue” requests to run all the time without setInterval?
I am reading data in realtime from a device through http requests, however the way I am currently doing it is, something like this:我正在通过 http 请求从设备实时读取数据,但是我目前这样做的方式是这样的:
setInterval(() => {
for (let request of requests) {
await request.GetData();
}
}, 1000);
However, sometimes there is lag in the network, and since there are 4-5 requests, sometimes they don't all finish within a second, so they start stacking up, until the device eventually starts to timeout, so I need to somehow get rid of the setInterval.但是,有时网络会出现延迟,由于有 4-5 个请求,有时它们不会在一秒钟内全部完成,所以它们开始堆叠,直到设备最终开始超时,所以我需要以某种方式得到摆脱 setInterval。 Increasing the time is not an option.
增加时间不是一种选择。
Essentially, I want them to get stuck in an infinite loop and I can add an inner timer to let the requests run again when half a second or a second has passed since the last run, but how do I get them stuck in an infinite loop without blocking the rest of the application?本质上,我希望它们陷入无限循环,我可以添加一个内部计时器,让请求在自上次运行后经过半秒或一秒后再次运行,但我如何让它们陷入无限循环不阻塞应用程序的rest?
Or maybe a way to make setInterval wait for all requests to finish before starting to count the 1 second interval?或者也许是一种让 setInterval 在开始计算 1 秒间隔之前等待所有请求完成的方法?
Try:尝试:
(async () => {
while (true) {
for (let request of requests) {
await request.GetData();
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
})();
This will only start waiting once all the requests are finished, preventing them from stacking up.这只会在所有请求完成后开始等待,防止它们堆积起来。
Alternatively, on the inside of the async function, use:或者,在异步 function 的内部,使用:
while (true) {
await Promise.all(requests.map(request => request.GetData()));
await new Promise((resolve) => setTimeout(resolve, 1000));
}
This is different because all the calls to request.GetData()
will run concurrently, which may or may not be what you want.这是不同的,因为对
request.GetData()
的所有调用都将同时运行,这可能是也可能不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.