Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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