Asynchronous HTTP requests

Sorry that I haven’t been on in a couple days. This topic came up in the gitter channel, and that is why I brought up the question. I have found a solution. As soon as I saw @Sija’s comment about the await_async shard, I remembered Crystal’s built-in Future implementation! Using this feature solves the issue IMO:

require "http"
addr = "https://jsonplaceholder.typicode.com/todos/1"
promise = future do
  HTTP::Client.get addr do |result|
    if result.status_code == 200
      IO.copy result.body_io, STDOUT
      puts "\n ^^ result from #{addr}"
    else
      puts "request failed with status #{result.status_code.inspect}"
    end
  end
end
puts "after the request"
promise.get
puts "after yielding the fiber"
1 Like