All Projects → RubenVerborgh → AsyncIterator

RubenVerborgh / AsyncIterator

Licence: other
An asynchronous iterator library for advanced object pipelines in JavaScript

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to AsyncIterator

Rubico
[a]synchronous functional programming
Stars: ✭ 133 (+209.3%)
Mutual labels:  asynchronous, iterator
spellbook
Functional library for Javascript
Stars: ✭ 14 (-67.44%)
Mutual labels:  asynchronous, iterator
Tributary
Streaming reactive and dataflow graphs in Python
Stars: ✭ 231 (+437.21%)
Mutual labels:  asynchronous
AsyncSuffix
Asynchronous methods naming checker for ReSharper
Stars: ✭ 19 (-55.81%)
Mutual labels:  asynchronous
Rump
REST client for Java that allows for easy configuration and default values. Allows for quick request construction and a huge range of modifications by using response/request interceptors, adjusting default values related to HTTP requests and creating custom instances for when you need multiple API connection setups.
Stars: ✭ 55 (+27.91%)
Mutual labels:  asynchronous
Specification
OpenMessaging Specification
Stars: ✭ 242 (+462.79%)
Mutual labels:  asynchronous
SandDB
A simple immutable database for the masses.
Stars: ✭ 21 (-51.16%)
Mutual labels:  asynchronous
Awaitility
Awaitility is a small Java DSL for synchronizing asynchronous operations
Stars: ✭ 2,800 (+6411.63%)
Mutual labels:  asynchronous
venusscript
A dynamic, interpreted, scripting language written in Java.
Stars: ✭ 17 (-60.47%)
Mutual labels:  asynchronous
PandaDemo
Demo project for asynchronous render and Layout framework Panda
Stars: ✭ 15 (-65.12%)
Mutual labels:  asynchronous
debugging-async-operations-in-nodejs
Example code to accompany my blog post on debugging async operations in Node.js.
Stars: ✭ 22 (-48.84%)
Mutual labels:  asynchronous
future.scala
Stack-safe asynchronous programming
Stars: ✭ 38 (-11.63%)
Mutual labels:  asynchronous
iterator-driver
迭代器驱动
Stars: ✭ 32 (-25.58%)
Mutual labels:  iterator
oh-my-design-patterns
🎨 Record the articles and code I wrote while learning design patterns
Stars: ✭ 33 (-23.26%)
Mutual labels:  iterator
Smallrye Mutiny
An Intuitive Event-Driven Reactive Programming Library for Java
Stars: ✭ 231 (+437.21%)
Mutual labels:  asynchronous
esa-httpclient
An asynchronous event-driven HTTP client based on netty.
Stars: ✭ 82 (+90.7%)
Mutual labels:  asynchronous
Coerce Rs
Coerce - an asynchronous (async/await) Actor runtime and cluster framework for Rust
Stars: ✭ 231 (+437.21%)
Mutual labels:  asynchronous
zab
C++20 liburing backed coroutine executor and event loop framework.
Stars: ✭ 54 (+25.58%)
Mutual labels:  asynchronous
promise4j
Fluent promise framework for Java
Stars: ✭ 20 (-53.49%)
Mutual labels:  asynchronous
asynckivy
async library for Kivy
Stars: ✭ 56 (+30.23%)
Mutual labels:  asynchronous

Asynchronous iterators for JavaScript

Build Status Coverage Status npm version

AsyncIterator is a lightweight JavaScript implementation of demand-driven object streams, and an alternative to the two-way flow controlled Node.js Stream. As opposed to Stream, you cannot push anything into an AsyncIterator; instead, an iterator pulls things from another iterator. This eliminates the need for expensive, complex flow control.

Read the full API documentation.

Data streams that only generate what you need

AsyncIterator allows functions to return multiple asynchronously and lazily created values. This adds a missing piece to JavaScript, which natively supports returning a single value synchronously and asynchronously (through Promise), but multiple values only synchronously (through Iterable):

  single value multiple values
synchronous T getValue() Iterable<T> getValues()
asynchronous Promise<T> getValue() AsyncIterator<T> getValues()

Like Iterable, an AsyncIterator only generates items when you ask it to. This contrast with patterns such as Observable, which are data-driven and don't wait for consumers to process items.

The asynchronous iterator interface

An asynchronous iterator is an object that exposes a series of data items by:

  • implementing EventEmitter
  • returning an item when you call iterator.read (yielding null when none is available at the moment)
  • informing when new items might be available through iterator.on('readable', callback)
  • informing when no more items will become available through iterator.on('end', callback)
  • streaming all of its items when you register through iterator.on('data', callback)

Any object that conforms to the above conditions can be used with the AsyncIterator library (this includes Node.js Streams). The AsyncIterator interface additionally exposes several other methods and properties.

Example: fetching Wikipedia links related to natural numbers

In the example below, we create an iterator of links found on Wikipedia pages for natural numbers.

import https from 'https';
import { resolve } from 'url';
import { IntegerIterator } from 'asynciterator';

// Iterate over the natural numbers
const numbers = new IntegerIterator({ start: 0, end: Infinity });
// Transform these numbers into Wikipedia URLs
const urls = numbers.map(n => `https://en.wikipedia.org/wiki/${n}`);
// Fetch each corresponding Wikipedia page
const pages = urls.transform((url, done, push) => {
  https.get(url, response => {
    let page = '';
    response.on('data', data => { page += data; });
    response.on('end',  () => { push(page); done(); });
  });
});
// Extract the links from each page
const links = pages.transform((page, done, push) => {
  let search = /href="([^"]+)"/g, match;
  while (match = search.exec(page))
    push(resolve('https://en.wikipedia.org/', match[1]));
  done();
});

We could display a link every 0.1 seconds:

setInterval(() => {
  const link = links.read();
  if (link)
    console.log(link);
}, 100);

Or we can get the first 30 links and display them:

links.take(30).on('data', console.log);

In both cases, pages from Wikipedia will only be fetched when needed—the data consumer is in control. This is what makes AsyncIterator lazy.

If we had implemented this using the Observable pattern, an entire flow of unnecessary pages would be fetched, because it is controlled by the data publisher instead.

Usage

AsyncIterator implements the EventEmitter interface and a superset of the Stream interface.

Consuming an AsyncIterator in on-demand mode

By default, an AsyncIterator is in on-demand mode, meaning it only generates items when asked to.

The read method returns the next item, or null when no item is available.

const numbers = new IntegerIterator({ start: 1, end: 2 });
console.log(numbers.read()); // 1
console.log(numbers.read()); // 2
console.log(numbers.read()); // null

If you receive null, you should wait until the next readable event before reading again. This event is not a guarantee that an item will be available.

links.on('readable', () => {
  let link;
  while (link = links.read())
    console.log(link);
});

The end event is emitted after you have read the last item from the iterator.

Consuming an AsyncIterator in flow mode

An AsyncIterator can be switched to flow mode by listening to the data event. In flow mode, iterators generate items as fast as possible.

const numbers = new IntegerIterator({ start: 1, end: 100 });
numbers.on('data', number => console.log('number', number));
numbers.on('end',  () => console.log('all done!'));

To switch back to on-demand mode, simply remove all data listeners.

Setting and reading properties

An AsyncIterator can have custom properties assigned to it, which are preserved when the iterator is cloned. This is useful to pass around metadata about the iterator.

const numbers = new IntegerIterator();
numbers.setProperty('rate', 1234);
console.log(numbers.getProperty('rate')); // 1234

const clone = numbers.clone();
console.log(clone.getProperty('rate'));   // 1234

numbers.setProperty('rate', 4567);
console.log(clone.getProperty('rate'));   // 4567

You can also attach a callback that will be called as soon as the property is set:

const numbers = new IntegerIterator();
numbers.getProperty('later', console.log);
numbers.setProperty('later', 'value');
// 'value'

License

The asynciterator library is copyrighted by Ruben Verborgh and released under the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].