Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created May 9, 2021 14:37
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 XoseLluis/08b9cfdbee89013fce037fb3d8c73a78 to your computer and use it in GitHub Desktop.
Save XoseLluis/08b9cfdbee89013fce037fb3d8c73a78 to your computer and use it in GitHub Desktop.
Leveraging ixjs AsyncIterable to apply sync and async functions via map, filter...
import { from as asyncIterableFrom } from 'ix/asynciterable/index.js';
import { filter as asyncFilter, map as asyncMap } from 'ix/asynciterable/operators/index.js';
function asyncSleep(interval){
return new Promise(resolveFn => setTimeout(resolveFn, interval));
}
async function findCountryForCityAsync(city){
let countries = [
{
name: "France",
mainCities: ["Toulouse", "Paris", "Lyon", "Marseille", "Bordeaux"]
},
{
name: "Belgium",
mainCities: ["Bruxelles", "Antwerp", "Liege"]
}
];
console.log("finding country for " + city);
await asyncSleep(2000);
let country = countries.find(country => country.mainCities.findIndex(_city => _city == city) > -1);
return country ? country.name : null;
}
let cities = ["Toulouse", "Paris", "Ghent", "Bruxelles"];
let transformedCitiesIterable = asyncIterableFrom(cities).pipe(
asyncMap(findCountryForCityAsync),
asyncFilter(city => city !== null),
asyncMap(x => x.toLocaleUpperCase())
);
console.log("transformedCitiesIterable type: " + transformedCitiesIterable.constructor.name);
//we have an objects chain like this:
// MapAsyncIterable -> FilterAsyncIterable -> MapAsyncIterable -> FromAsyncIterable
//async main
(async () => {
console.log("starting asyncIterableTest");
for await (let city of transformedCitiesIterable){
console.log(city);
}
console.log("ending asyncIterableTest");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment