跳转到内容

Future

异步操作结果。Future 由 funcs.async() 和 contract 异步调用返回。

不是可加载模块。Future 由异步操作创建:

local funcs = require("funcs")
local future, err = funcs.async("app.compute:task", data)

获取用于接收结果的通道:

local ch = future:response()
local payload, ok = ch:receive()
if ok then
local result = payload:data()
end

channel()response() 的别名。

非阻塞检查 future 是否已完成:

if future:is_complete() then
local result, err = future:result()
end

检查是否调用了 cancel()

if future:is_canceled() then
print("Operation was canceled")
end

获取缓存的结果(非阻塞):

local val, err = future:result()

返回:

  • 未完成: nil, nil
  • 已取消: nil, error(类型 CANCELED
  • 错误: nil, error
  • 成功: Payload, niltable, nil(多个 payload)

获取 future 失败时的错误:

local err, has_error = future:error()
if has_error then
print("Failed:", err:message())
end

返回: error, boolean

取消异步操作(尽力而为):

future:cancel()

如果操作已在进行中,仍可能完成。

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()
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
异步操作失败各异