Class: Cql::Promise

Inherits:
Object
  • Object
show all
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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePromise

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

#futureObject (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.

Parameters:

  • error (Error)

    the error which prevented the promise to be fulfilled



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.

Parameters:

  • value (Object) (defaults to: nil)

    the value of the future



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.

Parameters:



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.

Examples:

promise.try { 3 + 4 }
promise.future.value # => 7
promise.try do
  do_something_that_will_raise_an_error
end
promise.future.value # => (raises error)
promise.try('foo', 'bar', &proc_taking_two_arguments)

Yield Parameters:

  • ctx (Array)

    the arguments passed to #try



72
73
74
75
76
# File 'lib/cql/future.rb', line 72

def try(*ctx)
  fulfill(yield(*ctx))
rescue => e
  fail(e)
end