Created
June 18, 2018 00:57
-
-
Save camilleriluke/be93d4e5ffb984d48f0129cddca022fa to your computer and use it in GitHub Desktop.
AsyncIterator doodling
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
const sleep = ms => new Promise(r => setTimeout(r, ms)); | |
const numbersFromGenerator = fromI => { | |
let i = fromI; | |
return { | |
[Symbol.asyncIterator]: async function*() { | |
while (true) { | |
await sleep(500); | |
yield i++; | |
} | |
} | |
}; | |
}; | |
const printNumbersUntil = async fn => { | |
for await (const i of numbersFromGenerator(1)) { | |
console.log(`Next number is: ${i}`); | |
if (fn(i)) { | |
break; | |
} | |
} | |
}; | |
printNumbersUntil(x => x >= 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment