getify / monio

The most powerful IO monad implementation in JS, possibly in any language!
http://monio.run
MIT License
1.06k stars 58 forks source link

Parallel IO Tasks #20

Closed MalQaniss closed 2 years ago

MalQaniss commented 2 years ago

If we let's say want to send parallel requests with "Promise.all" would this be a fine way:

const planetsNums = ['1','2']
const getPlanet = num => IO(() => fetch(`https://swapi.dev/api/planets/${num}`).then(response => response.json()))

const data = await Promise.all([...planetsNums.map(num => getPlanet(num).run())])
console.log(data)
getify commented 2 years ago

Essentially, yes.

There's a helper in the IOHelpers module for this specific use-case, called waitAll(..). You'd use it in your example like this:

const planetsNums = ['1','2']
const getPlanet = num => IO(() => fetch(`https://swapi.dev/api/planets/${num}`).then(response => response.json()))

const data = await waitAll( ...planetsNums.map(getPlanet) ).run();
console.log(data);