Class: Ione::Promise

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

Since:

  • v1.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePromise

Returns a new instance of Promise

Since:

  • v1.0.0


18
19
20
# File 'lib/ione/future.rb', line 18

def initialize
  @future = CompletableFuture.new
end

Instance Attribute Details

#futureObject (readonly)

Since:

  • v1.0.0


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.

Since:

  • v1.0.0


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.

Since:

  • v1.0.0


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.

Since:

  • v1.0.0


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.

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

Since:

  • v1.0.0


76
77
78
79
80
# File 'lib/ione/future.rb', line 76

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