Created
November 14, 2018 23:35
-
-
Save DmitrySoshnikov/aa26573567b78ae414494e4d6b25aae7 to your computer and use it in GitHub Desktop.
async-iterators-example.js
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
/** | |
* Async iterators simple example. | |
* | |
* by Dmitry Soshnikov <[email protected]> | |
* 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