Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created November 14, 2018 23:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save DmitrySoshnikov/aa26573567b78ae414494e4d6b25aae7 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/aa26573567b78ae414494e4d6b25aae7 to your computer and use it in GitHub Desktop.
async-iterators-example.js
/**
* Async iterators simple example.
*
* by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
* MIT Style License, 2018
*/
async function* streamChunks() {
yield genChunk(1);
yield genChunk(2);
yield genChunk(3);
}
async function genChunk(v) {
const ms = v * 1000;
console.log(`Wating for ${ms} ms...`);
await sleep(ms);
return v;
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const genChunks = async () => {
for await (const chunk of streamChunks()) {
console.log(` - Received chunk: ${chunk}\n`);
}
console.log('Request finished.');
};
genChunks();
/*
Results:
Wating for 1000 ms...
- Received chunk: 1
Wating for 2000 ms...
- Received chunk: 2
Wating for 3000 ms...
- Received chunk: 3
Request finished.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment