Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call two async functions every `n` and `m` seconds within a `while (true)` loop?

I have the following loop:

while (true) {
  await f();
  await g();
}

where f and g are defined as follows:

async function f() {
    await Promise.all([SOME_REQUEST_F, sleep(1000)])
}

async function g() {
    await Promise.all([SOME_REQUEST_G, sleep(5000)])
}

Also sleep is defined as follows:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

My intention is to have SOME_REQUEST_F awaited every one second, and SOME_REQUEST_G awaited every five seconds, hence wrapping them in f and g.

However, currently g is blocking the re-awaiting of f within the loop.

How to define sleep, such that if used in g, it blocks re-execution of g, but not that of f? Is there a better way to do what I want?

like image 376
Atonal Avatar asked Mar 02 '19 23:03

Atonal


1 Answers

Use two while loops instead:

(async () => {
  setTimeout(async () => {
    while (true) {
      await f();
    }
  });
  while (true) {
    await g();
  }
})();

The setTimeout there is needed to allow both whiles to run concurrently, so that the initialization of one doesn't block the other from starting.

like image 109
CertainPerformance Avatar answered Sep 24 '22 09:09

CertainPerformance