Skip to content

Instantly share code, notes, and snippets.

@geovanisouza92
Last active September 25, 2018 14:36
Show Gist options
  • Save geovanisouza92/64b5a729b2012532f1c8852af182e8c8 to your computer and use it in GitHub Desktop.
Save geovanisouza92/64b5a729b2012532f1c8852af182e8c8 to your computer and use it in GitHub Desktop.
Async iterator for pagination
class Token {
nextRange() {
return `${this._range}-`;
}
feed(response) {
this._range = response.headers.Range;
}
}
class Request {
constructor(input) {
this._input = input;
}
paginationToken() {
return new Token();
}
do(token) {
return {
async next() {
const raw = await fetch(this._input, {
headers: {
'Content-Range': token.nextRange(),
}
});
return new Response(raw);
},
[Symbol.asyncIterator]() {
return this;
}
}
}
}
const request = new Request();
const token = request.paginationToken();
for await (const response of request.do(token)) {
// consume response.body
token.feed(response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment