Created
May 9, 2021 14:37
-
-
Save XoseLluis/08b9cfdbee89013fce037fb3d8c73a78 to your computer and use it in GitHub Desktop.
Leveraging ixjs AsyncIterable to apply sync and async functions via map, filter...
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
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