How to get results from Concurrent::Promise::all?

Viewed 152

Using conccurrent-ruby, how can I execute a set of promises and then get the results?

Here is an example of what I would like to be able to do (The test passes because it never reaches the 'then' block.

it "can aggregate the results" do
  Concurrent::Promise::all?(
    Concurrent::Promise.execute { 42 },
    Concurrent::Promise.execute { 43 },
  ).then do |result|
      binding.pry
      expect(result).to eq([42, 43])
    end
end
1 Answers

In order to execute the the .all? promises you need to call .execute and .wait, that means it will execute then wait until the result is ready, note wait is blocking meaning it will block your code`. ex:


Concurrent::Promise.all?(
  Concurrent::Promise.new { 42 },
  Concurrent::Promise.new { 43 }
).then do |result|
  puts 'finished promises'
end.execute.wait

However if you wish to get the results after the promises are finished you can use .zip method, ex:


Concurrent::Promise.zip(
  Concurrent::Promise.execute { 42 },
  Concurrent::Promise.execute { 43 }
).then do |result|
  expect(result).to eq([42, 43])
end.wait

Note: There are some differences between .zip and .all? check the docs: https://www.rubydoc.info/gems/concurrent-ruby/Concurrent/Promise

Related