Created
April 2, 2018 04:59
-
-
Save josmardias/a7a9d69e8833d43cc58f387c4255a88a to your computer and use it in GitHub Desktop.
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
(async () => { | |
// logs to just to make sure that stuff is really asynchronous | |
// setInterval(() => console.log('--'), 200) | |
function iterWrap(iter) { | |
return { | |
take: (n = 100) => { | |
function* limitedGenerator() { | |
for(let i = 0; i < n; i++) { | |
yield iter.next().value | |
} | |
} | |
return iterWrap(limitedGenerator()) | |
}, | |
toArray: (max = 100) => { | |
const buffer = [] | |
let next = { done: false } | |
for(let i = 0; i < max && !next.done; i++) { | |
next = iter.next() | |
buffer.push(next.value) | |
console.log(max, i, next, JSON.stringify(buffer)) | |
} | |
console.log(next) | |
return buffer | |
}, | |
} | |
} | |
// generator that yields promises | |
function* createIter(delay = 1000) { | |
let i = 0 | |
while(true) { | |
yield ( | |
new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(i++) | |
}, delay) | |
}) | |
) | |
} | |
} | |
// ---- main | |
const iter = iterWrap(createIter()) | |
for(let i = 0; i < 2; i++) { | |
const batch = iter.take(5).toArray() | |
const numbers = await Promise.all(batch) | |
console.log(numbers) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
huu hahaha
sir