Range Over Channels in JavaScript

In a previous example, we saw how for and of provide iteration over basic data structures. We can also use this syntax to iterate over values received from an asynchronous iterable.

async function main() {
    // We'll iterate over 2 values in the `queue` array.
    const queue = ['one', 'two'];
    
    // This `for...of` loop iterates over each element in the `queue`.
    // We use an async generator function to simulate a channel-like behavior.
    for await (const elem of (async function*() {
        for (const item of queue) {
            yield item;
        }
    })()) {
        console.log(elem);
    }
}

main();

To run the program:

$ node range-over-async-iterable.js
one
two

This example demonstrates how to use asynchronous iteration in JavaScript to simulate channel-like behavior. While JavaScript doesn’t have built-in channels like some other languages, we can use async generators and for await...of loops to achieve similar functionality.

The async generator function creates an iterable that yields each item in the queue. The for await...of loop then asynchronously iterates over these values, printing each one.

This approach allows us to work with asynchronous data streams in a way that’s syntactically similar to synchronous iteration, making it easier to write and understand asynchronous code.