Last active
September 25, 2018 14:36
-
-
Save geovanisouza92/64b5a729b2012532f1c8852af182e8c8 to your computer and use it in GitHub Desktop.
Async iterator for pagination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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