class Sync::Future(T)

Overview

An object that will eventually hold a value.

You can for example delegate the computation of a value to another fiber, that can resolve is asynchronously, without blocking the current fiber, that can regularly poll for the value, or explicitly wait until the value is resolved.

For example:

result = Future(Int32).new

spawn do
  result.set(compute_some_value)
rescue exception
  result.fail(exception)
end

loop do
  do_something

  if value = result.get?
    p value
    break
  end
end

Defined in:

future.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new #

[View source]

Instance Method Detail

def fail(reason : Exception | String | Nil = nil) : Nil #

Sets the future as failed, then wakes up pending fibers.

Raises a RuntimeError if the future has already been resolved or has already failed.


[View source]
def get : T #

Returns the value. Blocks the current fiber until the future is resolved. Raises an exception if the future has failed.


[View source]
def get? : T | Nil #

Returns the value if resolved, otherwise returns nil immediately. Raises an exception if the future has failed.


[View source]
def set(value : T) : T #

Sets the value, then wakes up pending fibers.

Raises a RuntimeError if the future has already been resolved or has already failed.


[View source]