Skip to content

Instantly share code, notes, and snippets.

@padcom
Created April 17, 2024 09:33
Show Gist options
  • Save padcom/fa58be655d2860b0ccd2f545b4f48548 to your computer and use it in GitHub Desktop.
Save padcom/fa58be655d2860b0ccd2f545b4f48548 to your computer and use it in GitHub Desktop.
Streams using async generators
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