Skip to content

Consuming data

The return result of run() (or something else that makes a chain) is a regular Javascript asynchronous generator. This means you can use a for .. of loop or step through it manually.

// Read a value from the array every 100ms
const chain = Chains.From.array([1,2,3,4,5], 100);
for await (const value of chain) {
// ... do something with value
}

In the above pattern, execution of code finishes after the array is exhausted. However, chains can be infinite - eg a chain that has an event as a source. Be mindful that if for await is used, code after the loop may never run.

An alternative means of access is using ixfx’s asCallback , which, if you don’t prefix it with await, continues execution.

Chains.asCallback((chain, value) => {
// ...do something with value
});
// Execution continues, even while
// data gets printed

You can also optionally provide a third parameter to be notified asynchronously when the chain is completed:

Chains.asCallback((chain, value) => {
// ...do something with a value
}, () => {
// ...do something when 'chain' ends
});

The for..of pattern is not always appropriate. In some cases you want to essentially read the value from the chain on demand. asValue handles this, providing a function to read the latest value from the chain.

// Set it up
const readChain = Chains.asValue(chain);
...
// Some point later, read the value
const currentValue = await readChain();

When initialising, you can also provide an initial value. This is useful for chains where the source is based on an event that perhaps has not fired yet, but you still want a usable value when reading.

const readChain = Chains.asValue(chain, {x:0.5,y:0.5});

All data from a chain can be accumulated into an array:

const values = await Chains.asArray(chain);

If the chain is infinite (never ends), be sure to provide some limits:

// Stop after we have five items
const values = await asArray(chain, { limit: 5 });
// Stop after 5 seconds has elapsed
const values = await asArray(chain, { elapsed: 5000 });

asArray returns a new array, and is meant to be used with await so execution only continues when the data is fully read.

Alternatively you can add to an existing array over time using addToArray .

const data = []; // An array to add items to
Chains.addToArray(data, chain); // Add values from 'chain' into 'data'
// Execution continues, with `data` growing as values are yielded from the chain