Forked from DmitrySoshnikov/async-iterators-example.js
Created
February 2, 2019 05:51
-
-
Save jrgcubano/24f79c15f4e8d272baaa515e083ee6e2 to your computer and use it in GitHub Desktop.
async-iterators-example.js
This file contains hidden or 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