Is there a better way to make multiple HTTP requests asynchronously in Ruby?

http, ruby, sendasynchronousrequest

Solution

Instead of the while clause you used, you can call Thread#join to make the main thread wait for other threads.

threads = []
urls.each_value do |thing|
    threads << Thread.new do
        result = Net::HTTP.get(URI.parse(thing))
        json_stuff = JSON::parse(result)
        info = json["person"]["bio"]["info"]

        thing["name"] = info
    end
end

# Wait until threads are done.
threads.each { |aThread|  aThread.join }

Problem

I'm trying to make multiple HTTP requests in Ruby. I know it can be done in NodeJS quite easily. I'm trying to do it in Ruby using threads, but I don't know if that's the best way. I haven't had a successful run for high numbers of requests (e.g. over 50). ``` require 'json' require 'net/http' urls = [ {"link" => "url1"}, {"link" => "url2"}, {"link" => "url3"} ] urls.each_value do |thing| Thread.new do result = Net::HTTP.get(URI.parse(thing)) json_stuff = JSON::parse(result) info = json["person"]["bio"]["info"] thing["name"] = info end end # Wait until threads are done. while !urls.all? { |url| url.has_key? "name" }; end puts urls ``` Any thoughts?

Original source