If your question is "what is a basic example of the async
gem", then your second code snippet is one.
If your question is "why is the API like this?", that's something you'd likely have to ask the developer(s) working on this gem on its issue board.
If your question is "how can you tell if running an Async::Reactor
(which is what Kernel#Async
does) will be blocking, you can call Async#Task.current?
:
require 'async'
require 'net/http'
def log_whether_blocking
if Async::Task.current?
puts "Async::Task#current? is truthy, calling `Kernel#Async` will not block"
else
puts "Async::Task#current? is falsey, calling `Kernel#Async` will block"
end
end
n = 10
Async do
n.times do |i|
log_whether_blocking
Async do
Net::HTTP.get(URI("https://httpbin.org/delay/1.6"))
end
end
end
n.times do |i|
log_whether_blocking
Async do
Net::HTTP.get(URI("https://httpbin.org/delay/1.6"))
end
end
This gives the output
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is truthy, calling `Kernel#Async` will not block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
Async::Task#current? is falsey, calling `Kernel#Async` will block
While it may be a potential footgun for those unfamiliar with the API, you can always ensure running a set of Async::Reactor
s will be done concurrently if you wrap it in a Kernel#Async
call, though in some cases it may be an unnecessary to do so.
Async
will be blocked – Unemployable.rb
file (tryputs to_s
). Anything in themodule
orclass
block is not top level. – Unemployable