Skip to content

V2: utils: asGen()

Eugene Lazutkin edited this page Aug 3, 2022 · 1 revision

(Since 2.2.0) It is a utility to build pipelines from a list of functions (including asynchronous ones, generators, and asynchronous generators) bypassing the streaming framework and packaging it as an asynchronous generator function, which can work on Node 10 and up.

If your target is Node 8 or in general yo don't want to deal with generators, you may consider asFun(), which wraps everything in an asynchronous function.

asGen(...fns)

This is the main function of the module. It takes functions as arguments and builds a pipeline connecting them. The result is presented as an asynchronous generator function.

The first argument can be an iterator object or an asynchronous iterator object, which serves as a source of data. Usually, in this case, the returned function is called without a value (because it will be ignored anyway).

const {chain, none, final} = require('stream-chain');
const {asGen} = require('stream-chain/utils/asGen');

const pipeline = asGen(
  x => x % 2 == 0 ? none : x,
  x => x === 1 ? final(1) : x;
  x => x * x
);

// in async context:
const data = [1, 2, 3, 4, 5];
for (const value of data) {
  for await (const result of pipeline(value)) {
    console.log(result);
  }
}
// 1, 9, 25

Static properties

The following static properties are available:

  • next(value, fns, index)

All of them are documented below.

Additionally, the following properties are imported from defs module:

  • none,
  • final(value),
  • isFinal(value),
  • getFinalValue(value),
  • many(array).
  • isMany(value),
  • getManyValues(value)

Presently all these properties are documented in defs.

next(value, fns, index)

This is the workhorse of the module. It takes the following arguments:

  • value — any suitable value for a processing.
  • fns — an array of functions to pass value through. It can be any functions including asynchronous ones, generators, or asynchronous generators.
  • index — a non-negative integer value, which serves an index in fns to start the processing from. Usually, it is used for recursive calls, while users start processing from 0.

next() returns an asynchronous generator function.

Clone this wiki locally