Skip to content

Instantly share code, notes, and snippets.

@mariusGundersen
Created December 22, 2017 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariusGundersen/d08b8bd65d7915af0daf2bc70946371a to your computer and use it in GitHub Desktop.
Save mariusGundersen/d08b8bd65d7915af0daf2bc70946371a to your computer and use it in GitHub Desktop.
async-iterator-stream
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