Skip to content

Consuming data

Iterating

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

for await (const coord of xy) {
// Prints out the {x,y} value when a
// 'pointermove' happens.
console.log(coord);
}
// Execution does not continue

In the above pattern, execution of code after the for await unless the chain ends. In this case, since the source is an event, it will never end.

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

Chains.asCallback(xy, coord => {
console.log(coord);
});
// 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 values
}, () => {
// do something when 'chain' ends
});

Reading values

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});

Accumulating

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