Last active
August 23, 2019 19:09
-
-
Save rickpeyton/809f043651c496688bf079c13642e3f8 to your computer and use it in GitHub Desktop.
Concurrent-Ruby Promises Example
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
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