Class: Cql::Promise
- Inherits:
-
Object
- Object
- Cql::Promise
- Defined in:
- lib/cql/future.rb
Overview
A promise of delivering a value some time in the future.
A promise is the write end of a Promise/Future pair. It can be fulfilled with a value or failed with an error. The value can be read through the future returned by #future.
Direct Known Subclasses
Instance Attribute Summary collapse
-
#future ⇒ Object
readonly
Returns the value of attribute future.
Instance Method Summary collapse
-
#fail(error) ⇒ Object
Fails the promise.
-
#fulfill(value = nil) ⇒ Object
Fulfills the promise.
-
#initialize ⇒ Promise
constructor
A new instance of Promise.
-
#observe(future) ⇒ Object
Observe a future and fulfill the promise with the future’s value when the future resolves, or fail with the future’s error when the future fails.
-
#try(*ctx) {|ctx| ... } ⇒ Object
Run the given block and fulfill this promise with its result.
Constructor Details
#initialize ⇒ Promise
Returns a new instance of Promise.
19 20 21 |
# File 'lib/cql/future.rb', line 19 def initialize @future = CompletableFuture.new end |
Instance Attribute Details
#future ⇒ Object (readonly)
Returns the value of attribute future.
17 18 19 |
# File 'lib/cql/future.rb', line 17 def future @future end |
Instance Method Details
#fail(error) ⇒ Object
Fails the promise.
This will fail this promise’s future, and trigger all listeners of that future.
40 41 42 |
# File 'lib/cql/future.rb', line 40 def fail(error) @future.fail(error) end |
#fulfill(value = nil) ⇒ Object
Fulfills the promise.
This will resolve this promise’s future, and trigger all listeners of that future. The value of the future will be the specified value, or nil if no value is specified.
30 31 32 |
# File 'lib/cql/future.rb', line 30 def fulfill(value=nil) @future.resolve(value) end |
#observe(future) ⇒ Object
Observe a future and fulfill the promise with the future’s value when the future resolves, or fail with the future’s error when the future fails.
48 49 50 51 |
# File 'lib/cql/future.rb', line 48 def observe(future) future.on_value { |v| fulfill(v) } future.on_failure { |e| fail(e) } end |
#try(*ctx) {|ctx| ... } ⇒ Object
Run the given block and fulfill this promise with its result. If the block raises an error, fail this promise with the error.
All arguments given will be passed onto the block.
72 73 74 75 76 |
# File 'lib/cql/future.rb', line 72 def try(*ctx) fulfill(yield(*ctx)) rescue => e fail(e) end |