Open
Description
Reading the guide for the Promises work in 1.1.x I came across the fantastic Concurrent::Promises.zip
method.
It's interface, per the guide, expects an array of Future
s and will return a final value of said array's values. This is beneficial, but what would make my (and I suspect many other's) code cleaner is to optionally accept a Hash
of promises instead of an Array
.
e.g.
map_of_work = {
multiply: Concurrent::Promises.future { 3*2 },
divide: Concurrent::Promises.future { 3/2 },
add: Concurrent::Promises.future { 3 + 2 },
subtract: Concurrent::Promises.future { 3 - 2 },
}
# => {:multiply=>#<Concurrent::Promises::Future:0x00007fc474fad8a0 pending>,
# :divide=>#<Concurrent::Promises::Future:0x00007fc474fad008 pending>,
# :add=>#<Concurrent::Promises::Future:0x00007fc474fa7d60 pending>,
# :subtract=>#<Concurrent::Promises::Future:0x00007fc474fa6ca8 pending>}
Concurrent::Promises.zip(map_of_work).value!
# => {:multiply=>6,
# :divide=>1,
# :add=>5,
# :subtract=>1}
Why? Because it's a common pattern in Javascript libraries[1][2], and thus my team.
Arrays are slightly more cumbersome where I have to remember that index 2 is always for the addition work. Should another developer prepend more Future
s to the array, we must not forget to change all the indexes referenced thereafter. With hashes, an :add
is always an :add
.