Async generator pattern
Meros uses async generators to provide a streaming API that works seamlessly with modern JavaScript:Async generators allow you to process parts as they arrive, rather than waiting for the entire response to complete. This is crucial for real-time applications and reducing time-to-first-byte latency.
The generate function
At the core of Meros is thegenerate async generator function:
- Reads chunks from the underlying stream
- Maintains a buffer for incomplete parts
- Yields complete parts immediately
- Handles boundary detection across chunk boundaries
Incremental parsing
Meros implements an intelligent buffering strategy to handle boundaries that might be split across chunks:How it works
- Chunk arrival: When a new chunk arrives, it’s appended to the buffer
- Boundary search: Meros searches for the boundary in both the new chunk and the accumulated buffer
- Part extraction: Once a boundary is found, everything before it is processed as a complete part
- Buffer reset: The buffer is updated to contain only the remaining unparsed data
Yield strategies
Meros offers two yield strategies controlled by themultiple option:
Default mode (eager yielding)
By default, Meros yields each part as soon as it’s parsed:- Lower latency - parts are available immediately
- One yield per part
- Ideal for streaming UIs that update incrementally
Batch mode (multiple: true)
Whenmultiple: true is set, Meros collects all parts from a chunk and yields them as an array:
When to use batch mode
Batch mode is an optimization for scenarios where you need to process multiple parts synchronously:- GraphQL stores: Update the store once with all patches from a chunk
- Bulk operations: Aggregate data before committing to a database
- Reduced overhead: Fewer async iterations mean less event loop overhead
As noted in the README (line 150-153), batch mode is particularly useful for GraphQL where you can commit multiple payloads to the store synchronously rather than across multiple process ticks.
Integration with reactive libraries
Because Meros returns an async generator, it integrates seamlessly with reactive programming libraries:RxJS example
from operator converts the async iterable into an Observable stream.
Relay integration
For GraphQL applications using Relay, Meros can be used directly in the network layer:Cleanup and resource management
Meros properly cleans up resources using a try/finally block:- Any remaining buffered parts are yielded
- The stream reader is properly cancelled
- Resources are freed even if iteration stops early