Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Created May 3, 2015 13:02
Show Gist options
  • Save jussi-kalliokoski/cb8a1a9f84a6e665da81 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/cb8a1a9f84a6e665da81 to your computer and use it in GitHub Desktop.
Async iterators!!!
async function mapAsync (iterator, fn) {
let result = [];
for ( let itemPromise of await iterator ) {
let item = await itemPromise;
result.push(await fn(item));
}
return result;
}
async function filterAsync (iterator, fn) {
let result = [];
for ( let itemPromise of await iterator ) {
let item = await itemPromise;
if ( await fn(item) ) {
result.push(item);
}
}
return result;
}
function * numbers () {
for ( let i = 0; i < 10; i++ ) {
yield Promise.resolve(i);
}
}
const pow2 = (n) => Promise.resolve(n * n);
const isDivisibleBy2 = (n) => Promise.resolve(n !== 0 && !(n % 2));
mapAsync(filterAsync(numbers(), isDivisibleBy2), pow2).then((list) => {
console.log(list); // [4,16,36,64]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment