Futures
Futures
Section titled “Futures”Asynchronous operation results. Futures are returned by funcs.async() and contract async calls.
Loading
Section titled “Loading”Not a loadable module. Futures are created by async operations:
local funcs = require("funcs")local future, err = funcs.async("app.compute:task", data)Response Channel
Section titled “Response Channel”Get channel for receiving result:
local ch = future:response()local payload, ok = ch:receive()if ok then local result = payload:data()endchannel() is an alias for response().
Completion Check
Section titled “Completion Check”Non-blocking check if future completed:
if future:is_complete() then local result, err = future:result()endCancellation Check
Section titled “Cancellation Check”Check if cancel() was called:
if future:is_canceled() then print("Operation was canceled")endGetting Result
Section titled “Getting Result”Get cached result (non-blocking):
local val, err = future:result()Returns:
- Not complete:
nil, nil - Canceled:
nil, error(kindCANCELED) - Error:
nil, error - Success:
Payload, nilortable, nil(multiple payloads)
Getting Error
Section titled “Getting Error”Get error if future failed:
local err, has_error = future:error()if has_error then print("Failed:", err:message())endReturns: error, boolean
Canceling
Section titled “Canceling”Cancel async operation (best-effort):
future:cancel()Operation may still complete if already in progress.
Timeout Pattern
Section titled “Timeout Pattern”local future = funcs.async("app.compute:slow", data)local timeout = time.after("5s")
local r = channel.select { future:channel():case_receive(), timeout:case_receive()}
if r.channel == timeout then future:cancel() return nil, errors.new("TIMEOUT", "Operation timed out")end
return r.value:data()First-to-Complete
Section titled “First-to-Complete”local f1 = funcs.async("app.cache:get", key)local f2 = funcs.async("app.db:get", key)
local r = channel.select { f1:channel():case_receive(), f2:channel():case_receive()}
-- Cancel the slower oneif r.channel == f1:channel() then f2:cancel()else f1:cancel()end
return r.value:data()Errors
Section titled “Errors”| Condition | Kind |
|---|---|
| Operation canceled | CANCELED |
| Async operation failed | varies |