Class: Ione::Promise
- Inherits:
-
Object
- Object
- Ione::Promise
- Defined in:
- lib/ione/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.
Instance Attribute Summary collapse
- #future ⇒ Object readonly
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.
18 19 20 |
# File 'lib/ione/future.rb', line 18 def initialize @future = CompletableFuture.new end |
Instance Attribute Details
#future ⇒ Object (readonly)
16 17 18 |
# File 'lib/ione/future.rb', line 16 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.
39 40 41 |
# File 'lib/ione/future.rb', line 39 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.
29 30 31 |
# File 'lib/ione/future.rb', line 29 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.
47 48 49 50 51 52 53 54 55 |
# File 'lib/ione/future.rb', line 47 def observe(future) future.on_complete do |v, e| if e fail(e) else fulfill(v) end end 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.
76 77 78 79 80 |
# File 'lib/ione/future.rb', line 76 def try(*ctx) fulfill(yield(*ctx)) rescue => e fail(e) end |