Created
April 17, 2024 09:33
-
-
Save padcom/fa58be655d2860b0ccd2f545b4f48548 to your computer and use it in GitHub Desktop.
Streams using async generators
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 { pipeline } from 'stream/promises' | |
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) | |
const colorsGenerator = async function* () { | |
const values = [ 'yellow', 'orange', 'red', 'blue', 'purple', 'green' ] | |
for await (const color of values) { | |
yield color | |
await sleep(1000) | |
} | |
} | |
const wordUpperCaser = async function* (source) { | |
for await (const chunk of source) { | |
yield chunk.toUpperCase() | |
} | |
} | |
const letterUnderscorer = async function* (source) { | |
for await (const chunk of source) { | |
yield chunk.split('').join('_') | |
} | |
} | |
const chunkLogger = async function (source) { | |
for await (const chunk of source) { | |
console.log(chunk) | |
} | |
} | |
await pipeline(colorsGenerator, wordUpperCaser, letterUnderscorer, chunkLogger) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment