combine-async-iterators
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.1 • Public • Published

    Combine-async-iterators

    version MIT size Known Vulnerabilities

    Combine Multiple Asynchronous Iterators in one (not a sequence). It use Promise.race under the hood (the code idea is from Targos).

    ⚠️ This package was mainly built to work with native Asynchronous Generators (Iterators).

    Requirements

    Getting Started

    This package is available in the Node Package Repository and can be easily installed with npm or yarn.

    $ npm i combine-async-iterators
    # or
    $ yarn add combine-async-iterators

    Usage example

    const { promisify } = require("util");
    const combineAsyncIterators = require("combine-async-iterators");
    
    const sleep = promisify(setTimeout);
    
    async function* getValues(id) {
        for (let count = 0; count < 5; count++) {
            await sleep(Math.ceil(Math.random() * 1000));
            yield `${id}_${count}`;
        }
    }
    
    async function main() {
        const asyncIterator = combineAsyncIterators({}, getValues("first"), getValues("second"));
        for await (const value of asyncIterator) {
            console.log(value);
        }
    }
    main().catch(console.error);

    Since 2.0.0 it is also possible to recover errors through a callback. By default the method is stopped when an error is thrown (the throwError parameter allow to disable this behaviour).

    function errorCallback(err) {
        console.error("got you:", err);
    }
    
    const iteratorOptions = { errorCallback, throwError: false };
    const asyncIterator = combineAsyncIterators(iteratorOptions, getValues("first"), getValues("second"));
    for await (const value of asyncIterator) {
        console.log(value);
    }

    API

    declare function combineAsyncIterators(
        ...iterators: AsyncIterableIterator<any>[]
    ): AsyncIterableIterator<any>;
    
    declare namespace combineAsyncIterators {
        interface CombineOptions {
            throwError?: boolean;
            errorCallback?: (err: Error, index: number) => any;
        }
    }
    
    declare function combineAsyncIterators(
        options: combineAsyncIterators.CombineOptions,
        ...iterators: AsyncIterableIterator<any>[]
    ): AsyncIterableIterator<any>;
    
    export = combineAsyncIterators;

    Licence

    MIT

    Install

    npm i combine-async-iterators

    DownloadsWeekly Downloads

    1,939

    Version

    2.0.1

    License

    MIT

    Unpacked Size

    7.2 kB

    Total Files

    5

    Last publish

    Collaborators

    • fraxken