highland icon indicating copy to clipboard operation
highland copied to clipboard

Returning an async iterable

Open timwis opened this issue 5 years ago • 1 comments

Hi! Is it possible to get an async iterable from a highland object? I'd like to be able to consume it with for-await-of if possible.

timwis avatar May 12 '20 14:05 timwis

Yes, it is possible. The trick is to transform your highland stream into a Node Readable stream which automatically implements the Symbol.asyncIterable method.

const stream = require("highland");

// Just an example to simulate async work
function delay (ms) {
  return x => stream(push => {
    setTimeout(() => {
      push(null, x);
      push(null, stream.nil);
    }, ms);
  });
}

const source = stream([ 1, 2, 3 ])
  .flatMap(delay(1000));

(async () => {
  for await (let value of source.toNodeStream({ objectMode: true })) {
    console.log(value);
  }
})();

jaidetree avatar May 12 '20 17:05 jaidetree