Luvit port of Dart Future
Follow lua exception pattern, our Future always has an ok
flag plus a value
. if future failed, then
the then
callback called with false
plus string with error message, otherwise true
plus value
.
local Future = require("future").Future
local Completer = require("future").Completer
local wait = require("future").wait
local timer = require("timer")
local function getTimeoutFuture()
local completer = Completer:new()
timer.setTimeout(1000, function()
completer:complete(true, 100)
end)
return completer:getFuture()
end
getTimeoutFuture()
:on(function(ok, val)
if ok then
p(val)
else
p("error!", val)
end
end)
:transform(function(ok, val)
if not ok then
return ok, val
end
return ok, val + 100
end)
:chain(function(ok, val)
if not ok then
return Future.immediate(false, val)
end
local completer = Completer:new()
timer.setTimeout(100, function()
completer:complete(true, val .. " wait 100ms")
end)
return completer:getFuture()
end)
:on(p)
-- An immediate future
f = Future.immediate(true, 'immediate')
f:on(p)
-- wait futures
f = wait(getTimeoutFuture(), getTimeoutFuture())
f:on(p)