Created
December 22, 2017 15:40
-
-
Save mariusGundersen/d08b8bd65d7915af0daf2bc70946371a to your computer and use it in GitHub Desktop.
async-iterator-stream
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 function* source(){ | |
let n = 1; | |
while(true){ | |
yield n++; | |
await new Promise(res => setTimeout(res, 100)); | |
} | |
} | |
async function* map(func){ | |
for await(const chunk of this){ | |
yield await func(chunk); | |
} | |
} | |
async function* take(count){ | |
for await(const chunk of this){ | |
if(count-- <= 0) break; | |
yield chunk; | |
} | |
} | |
async function reduce(func, initial){ | |
for await(const chunk of this){ | |
initial = func(initial, chunk); | |
} | |
return initial; | |
} | |
async function run(){ | |
console.log('start'); | |
const result = await source() | |
::map(t => t*2) | |
::take(3) | |
::reduce((a, b) => a+b, 0); | |
console.log('done', result); | |
} | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment