Skip to content

Instantly share code, notes, and snippets.

@callmehiphop
Created July 1, 2019 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callmehiphop/4d6a334a0c2f152940e5b3b22dfd1ea0 to your computer and use it in GitHub Desktop.
Save callmehiphop/4d6a334a0c2f152940e5b3b22dfd1ea0 to your computer and use it in GitHub Desktop.
const {Readable} = require('stream');
class PageStream extends Readable {
constructor(requestFn) {
super({objectMode: true});
this.request = requestFn;
this.nextQuery = {};
this.pending = [];
}
async _read() {
if (!this.pending.length) {
if (!this.nextQuery) {
this.push(null);
return;
}
const [results, nextQuery] = await this.request(this.nextQuery);
this.pending = results;
this.nextQuery = nextQuery;
}
let more = true;
while (more && this.pending.length) {
more = this.push(this.pending.shift());
}
if (more) {
setImmediate(() => this._read());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment