Skip to content

Instantly share code, notes, and snippets.

@rickpeyton
Last active August 23, 2019 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickpeyton/809f043651c496688bf079c13642e3f8 to your computer and use it in GitHub Desktop.
Save rickpeyton/809f043651c496688bf079c13642e3f8 to your computer and use it in GitHub Desktop.
Concurrent-Ruby Promises Example
require "bundler/inline"
# https://ruby-concurrency.github.io/concurrent-ruby/1.1.4/Concurrent/Promise.html
gemfile do
source "https://rubygems.org"
gem "concurrent-ruby"
gem "http"
gem "logger"
gem "pry"
end
URL = "http://slowwly.robertomurray.co.uk/delay/3000/url/http://www.google.com".freeze
LOGGER = Logger.new("./concurrent_test.log")
EXECUTOR = Concurrent::FixedThreadPool.new(5)
def external_calls(counter, executor, logger)
Concurrent::Promise.new(executor: executor) { HTTP.get(URL) }
.then { HTTP.get(URL) }
.then { HTTP.get(URL) }
.then { |response| logger.info "#{counter}: #{response.code}" }
.on_error { |e| logger.error "#{counter}: #{e}" }
.execute
end
(0..5).map { |i| external_calls(i, EXECUTOR, LOGGER) }.each(&:wait)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment