Created
November 6, 2019 21:35
-
-
Save davidmyersdev/9b9ae67810e021e82604231be4abb716 to your computer and use it in GitHub Desktop.
A rudimentary implementation of promises for Ruby.
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 Promise | |
def initialize(&callback) | |
@callback = callback | |
@next_promise = nil | |
end | |
def resolve(callback_result = nil) | |
callback.call(callback_result).tap do |result| | |
next_promise.resolve(result) if next_promise | |
end | |
end | |
def then(&callback) | |
self.next_promise = self.class.new(&callback) | |
end | |
private | |
attr_accessor :callback, :next_promise | |
end | |
promise = Promise.new do | |
puts 'first' | |
end | |
puts 'procedural' | |
other_promise = promise.then do | |
puts 'second' | |
end | |
other_promise.then do | |
puts 'third' | |
end | |
promise.resolve | |
# prints | |
# => procedural | |
# => first | |
# => second | |
# => third |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment