How to send http requests with Channels?

Hi guys!

I`m trying to make 5 requests at once and here is my code:

require "http/client"

channel = Channel(String).new
list = %w[
  https://www.akitaonrails.com/
  https://citizen428.net/
  https://crystal-lang.org/
  https://www.akitaonrails.com/
  https://citizen428.net/
  https://crystal-lang.org/
]

list.each do |url|
  spawn do
    response = HTTP::Client.get(url)
    channel.send response.body
  end
end

puts channel.receive

Instead I have only 1 response)

The gist of it is you only get a single response because you only ever call channel.receive once. If you want it to print all of them, you need to call it the same amount of times as there were requests. E.g.

list.size.times do
  puts channel.receive
end
3 Likes

Y a my best friend ^_^
Thanks!)))))