0

I have this code:

for await (const thing of signal()) {
    // logic
}

for await (const thing of anotherSignal()) {
    // logic
}

The problem is that these for awaits run forever. So the second one never executes. Is there a way to make these 2 loops run in parallel?

  • 6
    See `Promise.all` https://stackoverflow.com/a/35612484/4781975 – Zooly Nov 09 '21 at 08:48
  • 2
    In parallel as in two threads or just running and reporting ASAP but leaving time for the other loop to also work? – VLAZ Nov 09 '21 at 08:49
  • 3
    @Zooly OP indicates those functions supply infinite promises. You cannot wait for all of them to finish. – VLAZ Nov 09 '21 at 08:50
  • 2
    If they never finish just put them both inside an async function and run, but you will want to also handle errors inside these functions. – Keith Nov 09 '21 at 08:54
  • 1
    Maybe it would be better to switch to a different abstraction, Observables in particular (e.g. https://rxjs.dev/). – Felix Kling Nov 09 '21 at 09:14

1 Answers1

1

Don't wait for first task to complete, Run them parallel, Like So:

let delay = ms => new Promise(ok => setTimeout(ok, ms));
async function* infinit_iter() {
  for (let i = 0;; i++) {
    await delay(3000)
    yield i
  }
}

async function run(name, iter) {
  for await (let i of iter)
    console.log(name, i)
}

run("signal:", infinit_iter())
run("anotherSignal:", infinit_iter())
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Nur
  • 2,361
  • 2
  • 16
  • 34