Future
Future
Section titled “Future”非同期操作の結果。Futureはfuncs.async()およびコントラクト非同期呼び出しによって返されます。
ロード可能なモジュールではありません。Futureは非同期操作によって作成されます:
local funcs = require("funcs")local future, err = funcs.async("app.compute:task", data)レスポンスチャネル
Section titled “レスポンスチャネル”結果を受信するためのチャネルを取得:
local ch = future:response()local payload, ok = ch:receive()if ok then local result = payload:data()endchannel()はresponse()のエイリアス。
完了チェック
Section titled “完了チェック”Futureが完了したかどうかのノンブロッキングチェック:
if future:is_complete() then local result, err = future:result()endキャンセルチェック
Section titled “キャンセルチェック”cancel()が呼び出されたかどうかをチェック:
if future:is_canceled() then print("Operation was canceled")endキャッシュされた結果を取得(ノンブロッキング):
local val, err = future:result()戻り値:
- 未完了:
nil, nil - キャンセル済み:
nil, error(kindCANCELED) - エラー:
nil, error - 成功:
Payload, nilまたはtable, nil(複数ペイロード)
エラーの取得
Section titled “エラーの取得”Futureが失敗した場合のエラーを取得:
local err, has_error = future:error()if has_error then print("Failed:", err:message())end戻り値: error, boolean
非同期操作をキャンセル(ベストエフォート):
future:cancel()操作が既に進行中の場合でも完了する可能性あり。
タイムアウトパターン
Section titled “タイムアウトパターン”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()最初に完了したもの
Section titled “最初に完了したもの”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()}
-- 遅い方をキャンセルif r.channel == f1:channel() then f2:cancel()else f1:cancel()end
return r.value:data()| 条件 | 種別 |
|---|---|
| 操作がキャンセルされた | CANCELED |
| 非同期操作が失敗 | 様々 |