Skip to content
Advertisement

How can I Interleave / merge async iterables?

Suppose I have some async iterable objects like this:

JavaScript

And for completeness:

JavaScript

Now, suppose I can concat them like this:

JavaScript

The (first 9) items yielded will be:

JavaScript

But imagine that I do not care about the order, that a, b and c yield at different speeds, and that I want to yield as quickly as possible.

How can I rewrite this loop so that xs are yielded as soon as possible, ignoring order?


It is also possible that a, b or c are infinite sequences, so the solution must not require all elements to be buffered into an array.

Advertisement

Answer

There is no way to write this with a loop statement. async/await code always executes sequentially, to do things concurrently you need to use promise combinators directly. For plain promises, there’s Promise.all, for async iterators there is nothing (yet) so we need to write it on our own:

JavaScript

Notice that combine does not support passing values into next or cancellation through .throw or .return.

You can call it like

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement