# Documentation for gololang.Async

This module offers asynchronous programming helpers, especially execution context agnostic promises and futures. The provided APIs are orthogonal to the execution strategy: it is up to you to execute code from the same thread, from a separate thread, or by pushing new tasks to a service executor.

The functions and augmentations in this module often delegate to Java classes from `gololang.concurrent.async`.

## Structs

### FutureBridge¶

Bridge structure to hold a reference to a Golo future and a Java future.

Instances of this struct are being returned by the `enqueue` augmentation on `ExecutorService` instances. This essentially adds the ability to:

- use the Golo future for its composability, and
- use tha Java future to cancel a job.

##### Members

- `_goloFuture`
- `_javaFuture`

## Augmentations

### gololang.Async.types.FutureBridge¶

A set of forwarding augmentations for `FutureBridge` instances.

The provided functions all forward to Golo futures, while `cancel` forwards to a Java future.

#### cancel(this, mayInterruptIfRunning)¶

#### fallbackTo(this, future)¶

#### filter(this, pred)¶

#### flatMap(this, fun)¶

#### map(this, fun)¶

#### onFail(this, listener)¶

#### onSet(this, listener)¶

### gololang.concurrent.async.Future¶

Augmentation on the base `Future` objects provided by the `gololang.concurrent.async.Future` Java class.

#### fallbackTo(this, future)¶

Returns a fallback future:

- when this future is set, the returned future is set to the same value,
- when it fails, the returned future matches the success or failure of `future`.

#### filter(this, pred)¶

Returns a future that filters this future through the `pred` predicate function.

Suppose that this future is set to `v`:

- if `pred(v)` is `true`, then the result future is set to `v`,
- if `pred(v)` is `false`, then the result is failed to a `java.util.NoSuchElementException`.

If this future fails, so does the returned future.

#### flatMap(this, fun)¶

Similar to `map`, except that `fun` returns a future, not a value.

#### map(this, fun)¶

Returns a future whose value is mapped through the `fun` function.

If this future is set to `v`, then the returned future is set to `fun(v)`. If it fails, the returned future is also failed with the same exception.

### gololang.concurrent.async.Promise¶

Augmentation on the base `Promise` objects provided by the `gololang.concurrent.async.Promise` Java class.

The promise initialize method takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, then call resolve if everything worked, otherwise call reject:

    let myPromise = -> promise(): initialize(|resolve, reject| {
      if everythingTurnedOutFine is true {
        resolve("Stuff worked!")
      } else {
        reject(java.lang.Exception("Failed!"))
      }
    })

    myPromise()
      : onSet(|result| {
          println(result) # Stuff worked!
      })
      : onFail(|err| {
          println(err: getMessage()) # Failed!
      })

#### initialize(this, closure)¶

#### initializeWithinThread(this, closure)¶

You can define a promise which runs “stuff” inside a Thread

### java.util.concurrent.ExecutorService¶

Augmentations for `ExecutorService`.

#### enqueue(this, fun)¶

Submits a function `fun` to be executed by this scheduler, and returns a `FutureBridge`.

`fun` takes no parameters, and its return value is used as a future value.

The returned `FutureBridge`` behaves both as a composable Golo future and as a Java future that can be cancelled.

Here is a sample usage:

    # Enqueue some elaborated work
    let f = executor: enqueue({
      Thread.sleep(1000_L)
      return 666
    })

    # Watch what could happen
    f: onSet(|v| -> println(v)):
       onFail(|e| -> println(e: getMessage()))

    # ...but make it fail unless the CPU was too slow
    f: cancel(true)

## Functions

### all(futures)¶

Given a collection of futures, returns a future whose value is eventually a vector with the results of these futures.

Given:

    all([ setFuture(1), failedFuture(e) ])

this yields a future whose eventual value is:

    vector[1, e]

Results are accumulated as futures get resolved. The last completed future triggers the calls to `onSet`-registered listeners on the same thread.

### any(futures)¶

Given a collection of futures, returns a future whose value is set to the first completing future.

If all futures fail, then the returned future fails to a `java.util.NoSuchElementException`.

### failedFuture(throwable)¶

Returns a failed future to a `throwable` exception.

### promise()¶

Returns a new promise. Promise objects have the following useful methods.

- `set(value)`: sets the promise value. The value is ignored if the promise has already been set.
- `fail(exception)`: set the value to an exception.
- `get()`: returns the promise value. It returns a bogus `null` value if the promise is still undefined.
- `blockingGet()`: waits until the promise is set or failed, and returns the value.
- `future()`: returns a new future object on a promise.
- `isResolved()` and `isFailed()` query the promise status.

Future objects have the following methods.

- `onSet(|v| {...})`: registers a callback when the value is set, or executes it right now if it has already been set.
- `onFail(|e| {...})`: registers a callback when the corresponding promise fails with an exception.
- `isResolved()`, `isFailed()` `get()` and `blockingGet()` delegate to the promise implementation.

### reduce(futures, init, reducer)¶

Returns a future whose value is set to the reduction of a collection of futures.

- `futures` is a collection of futures, and
- `init` is the initial value, and
- `reducer` is the reducing function of the form `|acc, next| {...}`.

If any future fails, then the result future fails, too. Otherwise, the returned future is set to the accumulation of the values. Listeners callbacks get executed on the thread of the completing future which is either the last successful future or the first future to fail.

### setFuture(value)¶

Returns a future set to `value`.