Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh

OliverJAsh/example.ts

Last active Mar 31, 2020
Embed
What would you like to do?
async iterable operators (map, filter) using async generators
const getName = async function*() {
yield 'bob';
yield 'baz';
yield 'bar';
};
const getAge = (name: string) => {
const responseJson = fetch('https://httpbin.org/get')
.then(response => response.json())
// Let's pretend the API is returning an age for us
.then(() => Math.round(Math.random() * 100));
return responseJson;
};
// https://github.com/ReactiveX/IxJS/blob/3218613193258c4d817a4dcbf2423df0e070d516/src/asynciterable/operators/filter.ts
const filter = async function*<T, T2>(
source: AsyncIterable<T>,
predicate: (item: T, index: number) => boolean,
) {
let i = 0;
for await (const item of source) {
if (predicate(item, i++)) {
yield item;
}
}
};
// https://github.com/ReactiveX/IxJS/blob/3218613193258c4d817a4dcbf2423df0e070d516/src/asynciterable/operators/map.ts
const map = async function*<T, T2>(
source: AsyncIterable<T>,
selector: (item: T, index: number) => T2 | Promise<T2>,
) {
let i = 0;
for await (const item of source) {
const result = await selector(item, i++);
yield result;
}
};
const stringAsyncIterable = map(
filter(getName(), name => name === 'bob'),
name => getAge(name).then(age => `${name}'s current age: ${age}`),
);
(async () => {
for await (let value of stringAsyncIterable) {
console.log(value);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.