How do I wait for multiple asynchronous operations to finish before sending a response in Ruby on Rails?
<p>In some web dev I do, I have multiple operations beginning, like GET requests to external APIs, and I want them to both start at the same time because one doesn't rely on the result of the other. I want things to be able to run in the background. I found the <a href="https://github.com/ruby-concurrency/concurrent-ruby" rel="nofollow noreferrer">concurrent-ruby library</a> which seems to work well. By mixing it into a class you create, the class's methods have asynchronous versions which run on a background thread. This lead me to write code like the following, where FirstAsyncWorker and SecondAsyncWorker are classes I've coded, into which I've mixed the Concurrent::Async module, and coded a method named &quot;work&quot; which sends an HTTP request:</p>
<pre><code>def index
  op1_result = FirstAsyncWorker.new.async.work
  op2_result = SecondAsyncWorker.new.async.work
  
  render text: results(op1_result, op2_result)
end
</code></pre>
<p>However, the controller will implicitly render a response at the end of the action method's execution. So the response gets sent before op1_result and op2_result get values and the only thing sent to the browser is &quot;#&quot;.</p>
<p>My solution to this so far is to use Ruby threads. I write code like:</p>
<pre><code>def index
  op1_result = nil
  op2_result = nil

  op1 = Thread.new do
    op1_result = get_request_without_concurrent
  end

  op2 = Thread.new do
    op2_result = get_request_without_concurrent
  end

  # Wait for the two operations to finish
  op1.join
  op2.join

  render text: results(op1_result, op2_result)
end
</code></pre>
<p>I don't use a mutex because the two threads don't access the same memory. But I wonder if this is the best approach. Is there a better way to use the concurrent-ruby library, or other libraries better suited to this situation?</p>