Created
December 3, 2014 09:53
-
-
Save stefanoc/3aa89f2a7ad9fe30af51 to your computer and use it in GitHub Desktop.
Promises
This file contains hidden or 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 Promise | |
class << self | |
alias :make :new | |
end | |
def initialize(block) | |
@result = [] | |
@thread = Thread.new(@result) do |result| | |
result[0] = block.call | |
end | |
end | |
def result | |
@thread.join | |
@result[0] | |
end | |
end | |
def very_long_calculation | |
sleep 2 | |
42 | |
end | |
p = Promise.make(->{ very_long_calculation }) | |
puts "Doing something" | |
sleep 3 | |
puts "Done doing something" | |
puts p.result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment