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?

5
  • 6
    See Promise.all stackoverflow.com/a/35612484/4781975 Commented Nov 9, 2021 at 8:48
  • 2
    In parallel as in two threads or just running and reporting ASAP but leaving time for the other loop to also work? Commented Nov 9, 2021 at 8:49
  • 3
    @Zooly OP indicates those functions supply infinite promises. You cannot wait for all of them to finish. Commented Nov 9, 2021 at 8: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. Commented Nov 9, 2021 at 8:54
  • 1
    Maybe it would be better to switch to a different abstraction, Observables in particular (e.g. rxjs.dev). Commented Nov 9, 2021 at 9:14

1 Answer 1

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())

Sign up to request clarification or add additional context in comments.

1 Comment

What does "on demand" mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.