Last active
November 1, 2019 05:13
-
-
Save bradparker/9caa742fdd606411bd5cff269c6c6425 to your computer and use it in GitHub Desktop.
Flattening nested iterators ... for use with weird DynamoDB scan API
This file contains hidden or 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
const testItems = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
const limit = 2; | |
const getBatch = (cursor = null) => { | |
const currentCursor = cursor || 0; | |
const nextPotentialCursor = currentCursor + limit; | |
const nextCursor = nextPotentialCursor > 10 ? null : nextPotentialCursor; | |
return new Promise(resolve => | |
setTimeout(() => resolve({ | |
items: testItems.slice(currentCursor, nextCursor), | |
cursor: nextCursor | |
}), 5000) | |
); | |
}; | |
const getAll = async function* (cursor = null) { | |
const { cursor: nextCursor, items } = await getBatch(cursor); | |
yield* items; | |
if (nextCursor !== null) { | |
yield* getAll(nextCursor); | |
} | |
}; | |
const main = async () => { | |
for await (const item of getAll()) { | |
console.log(item); | |
} | |
} | |
main(); | |
/* | |
~ » node iterate.js | |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment