Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Convert a push API to an async iterator in JavaScript

17 Bridge a push API to a pull API

hard

Build an object you can push values into and for await values out of. It must work both ways round: values pushed before anyone reads are buffered, and a reader parked on next() is released by the next push or by close().

Stuck? Three hints, smallest first
  1. 1. Keep a buffer array and a single parked resolve function. At most one of the two is ever non-empty.
  2. 2. next(): if the buffer has something, resolve at once; if closed, report done; otherwise return a promise and remember its resolve.
  3. 3. push: if someone is parked, resolve them directly and skip the buffer.

The answer

function pushStream() {
  const buffer = [];
  let parked = null;
  let closed = false;
  return {
    push(value) {
      if (parked) { const release = parked; parked = null; release({ value, done: false }); }
      else buffer.push(value);
    },
    close() {
      closed = true;
      if (parked) { const release = parked; parked = null; release({ value: undefined, done: true }); }
    },
    [Symbol.asyncIterator]() {
      return {
        next: () => {
          if (buffer.length) return Promise.resolve({ value: buffer.shift(), done: false });
          if (closed) return Promise.resolve({ value: undefined, done: true });
          return new Promise((resolve) => { parked = resolve; });
        },
      };
    },
  };
}

const collect = async (source) => {
  const out = [];
  for await (const v of source) out.push(v);
  return out;
};

// Pushed first, read afterwards: the buffer path.
const early = pushStream();
early.push('a');
early.push('b');
early.close();
const buffered = await collect(early);

// Read first, pushed afterwards: the parked path.
const live = pushStream();
const reading = collect(live);
live.push('x');
live.push('y');
live.close();
const streamed = await reading;

// A reader parked with nothing coming is released by close().
const idle = pushStream();
const pending = collect(idle);
idle.close();
const nothing = await pending;

// And the buffer is still drained after close, which is a real wrinkle.
const late = pushStream();
late.close();
late.push('late');
const afterClose = await collect(late);

console.log('buffered :', buffered);
console.log('streamed :', streamed);
console.log('idle     :', nothing);
console.log('pushed after close:', afterClose, '<- still delivered');

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('values pushed before anyone reads are buffered', buffered, ['a', 'b']);
test('a reader parked on next() is released by the next push', streamed, ['x', 'y']);
test('closing while a reader is parked ends the loop with nothing', nothing, []);
test('this version still drains the buffer after close, which is a bug worth seeing', afterClose, ['late']);
test('it is a pull API on the outside', typeof early[Symbol.asyncIterator], 'function');
test('and nothing polls: next() returns a promise that someone else resolves', typeof pushStream()[Symbol.asyncIterator]().next().then, 'function');
test('a stream closed before use is simply empty', await collect((() => { const s = pushStream(); s.close(); return s; })()), []);

Everything that arrives from outside your program is a push: an event, a message, a webhook. Everything that reads nicely is a pull: for await. This little object is the adapter, and the whole of it is the invariant that the buffer and the parked resolver are never both occupied — if someone is waiting, hand the value straight over; if not, keep it.

The fourth assertion is deliberately a failure. next() checks the buffer before it checks closed, so a value pushed after close() is still delivered. Whether that is a bug depends on what you meant by close — "no more will be accepted" or "stop after what you have" — and the lesson is that you have to decide, because the naive ordering decides for you.

What this leaves out is backpressure. A producer that pushes faster than the consumer reads grows the buffer without limit, which is how a memory graph goes vertical. A real implementation caps the buffer and either drops, blocks the producer by returning a promise from push, or errors. The circular buffer in exercise 87 is the drop-oldest version of that decision.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.