Skip to content

Instantly share code, notes, and snippets.

@banister
Created May 18, 2015 15:15
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 banister/e8a7f94ad78bd76f80d8 to your computer and use it in GitHub Desktop.
Save banister/e8a7f94ad78bd76f80d8 to your computer and use it in GitHub Desktop.
require 'deferrable_gratification'
class Promise
def initialize
@df = EM::DefaultDeferrable.new
DG.enhance! EM::DefaultDeferrable
end
def done(&block)
tap { @df.callback(&block) }
end
def fail(&block)
tap { @df.errback(&block) }
end
def always(&block)
tap { @df.bothback(&block) }
end
def resolve(*args)
@df.succeed(*args)
end
def reject(*args)
@df.fail(*args)
end
def then(_done, _fail=nil)
df = Promise.new
done { |v| result = _done.call(v); df.resolve(result) }.
fail { |v| result = _fail.call(v); df.reject(result) }
df
end
def transform(_done, _fail=nil)
tap do
@df.transform(&_done)
@df.transform_error(&_fail) if _fail
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment