caolan / highland

High-level streams library for Node.js and the browser

Home Page:https://caolan.github.io/highland

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Returning an async iterable

timwis opened this issue · 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.

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