Created
February 25, 2020 11:41
-
-
Save tomfun/79eb67cff8a50364cf92015357e600fa to your computer and use it in GitHub Desktop.
Example of async generators with typescript
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
import { generateSequence } form './simple' | |
class NumberTransfrormer { | |
transform = async function*(gen: AsyncGenerator<number>) { | |
for await (const n of gen) { | |
yield n * 2; | |
} | |
} | |
} | |
// run | |
(async () => { | |
const multiplier = new HeaderFooterTransfrormer(); | |
for await (const value of multiplier.transform(multiplier.transform(generateSequence(1, 5)))) { | |
console.log(value); | |
} | |
})(); |
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
import { generateSequence } form './simple' | |
class NumberTransfrormer { | |
async *transform(gen: AsyncGenerator<number>): AsyncGenerator<number> { | |
for await (const n of gen) { | |
yield n * 2; | |
} | |
} | |
} | |
// run | |
(async () => { | |
const multiplier = new HeaderFooterTransfrormer(); | |
for await (const value of multiplier.transform(multiplier.transform(generateSequence(1, 5)))) { | |
console.log(value); | |
} | |
})(); |
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
export async function* generateSequence(start: number, end: number): AsyncGenerator<number> { | |
for (let i = start; i <= end; i++) { | |
await new Promise(resolve => setTimeout(resolve, 1000)); | |
yield i as number; | |
} | |
} | |
// run | |
(async () => { | |
for await (const value of generateSequence(1, 5)) { | |
console.log(value); // 1, then 2, then 3, then 4, then 5 | |
} | |
})(); |
Author
tomfun
commented
Feb 25, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment