Skip to content

Instantly share code, notes, and snippets.

@camilleriluke
Created June 18, 2018 00:57
Show Gist options
  • Save camilleriluke/be93d4e5ffb984d48f0129cddca022fa to your computer and use it in GitHub Desktop.
Save camilleriluke/be93d4e5ffb984d48f0129cddca022fa to your computer and use it in GitHub Desktop.
AsyncIterator doodling
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