Created
February 22, 2021 18:37
-
-
Save creadone/2a1080eef16c2a1835d009a8723066c1 to your computer and use it in GitHub Desktop.
Helper to wrap external API requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cocoon(T) | |
def initialize( | |
@result = Channel(T | Exception).new, | |
@output = Channel(T | Exception).new | |
) | |
end | |
def wrap(&block : -> T) forall T | |
spawn(name: "executor") do | |
@result.send block.call | |
rescue e | |
@result.send e | |
end | |
Fiber.yield | |
spawn(name: "receiver") do | |
select | |
when data = @result.receive | |
@output.send data | |
end | |
end | |
@output | |
end | |
end | |
# ----- | |
cocoon = Cocoon(HTTP::Client::Response).new | |
result = cocoon.wrap do | |
HTTP::Client.get "localhost:9292" | |
end | |
result.receive | |
#=> <HTTP::Client::Response...> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment