async
Asynchronous workers and tasks
Import
_ <- fat.async
Types
The async
library introduces two types: Worker
and Task
Worker
The Worker
is a simple wrapper around an asynchronous operation.
Constructor
Name | Signature | Brief |
---|---|---|
Worker | (task: Method) | Builds a Worker in standby mode |
Prototype members
Name | Signature | Brief |
---|---|---|
start | (): Worker | Begins the task |
cancel | (): Void | Cancels the task |
await | (): Worker | Waits for task completion |
isDone | (): Boolean | Checks if the task has completed |
hasStarted | Boolean | Set by start method |
hasAwaited | Boolean | Set by await method |
isCanceled | Boolean | Set by cancel method |
result | Any | Set by await method |
Task
A Task
represents a time-constrained asynchronous operation. It uses two Workers, one for the task itself and another for the timeout timer.
Constructor
Name | Signature | Brief |
---|---|---|
Task | (task: Method, wait: Number) | Builds a Task in standby mode |
The Task
constructor takes two arguments:
- task: The method to be executed asynchronously (the method may not take arguments directly, but you may curry those in using two arrows on the definition
-> ->
). - wait (optional): The timeout in milliseconds. If the task does not finish within this time, it is cancelled. The default is 40,000ms (40 seconds).
Prototype members
Name | Signature | Brief |
---|---|---|
start | (): Task | Begins the task and its timer |
cancel | (): Void | Cancels the task and its timer |
await | (): Task | Waits for task completion or timeout |
isDone | Boolean | Set true if task has been completed |
hasTimedOut | Boolean | Set true if task timed out |
result | Any | Set by await method |
Standalone Method
Name | Signature | Brief |
---|---|---|
selfCancel | (): * | Terminates the execution of the thread |
Usage Notes
Worker
instances are mapped to system threads on a one-to-one basis and get executed as per the system's scheduling. This implies that their execution may not always be immediate. To wait for the result of a Worker
or Task
, employ the await
method.
Examples
_ <- fat.async
math <- fat.math
time <- fat.time
# Define a slow task
slowTask = -> {
waitTime = math.random * 5000 # Wait up to 5 seconds
time.wait(waitTime)
waitTime
}
# Start the task as a Worker
worker = Worker(slowTask).start
# Get the worker result
result1 = worker.await.result # blocks until task is done
# Start a task with timeout
task = Task(slowTask, 3000).start
# Get the task result
result2 = task.await.result # blocks until task is done or timeout occurs
the Task's
await
method will raiseAsyncError
if the task times out before completion