简体   繁体   中英

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:

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. 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?

Or maybe a way to make setInterval wait for all requests to finish before starting to count the 1 second interval?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM