Skip to main content

Luau Futures

A future represents a read-only asynchronous value, one that may not have finished computation yet. A basic future could look like:

local Futures = require("@packages/Futures")
local Future = Futures.Future

local myFuture = Future.new(function()
yield()
return 1, 2, 3
end)

When you create a future, it wont begin execution until it is either polled or awaited.

Polling will advance the future to it's next resumption point every time that it is called, returning a [Poll] to let you check the status of the future.

If the Poll is ready, you can also unwrap it to get the [Result].

local poll = myFuture:poll()
if poll:isReady() then
local result = poll:unwrap()
-- Handle result
end

Awaiting a future will yield the current thread until the future finishes execution. As such, it is recommended that you only use the await method within other futures, preferring to use poll instead.

local result = myFuture:await()
-- Handle result

To read the result, you can use [Result:isOk] or [Result:isErr] to check what type the Result is.

You can then use [Result:unwrapOk] or [Result:unwrapErr] to get the value of the result.

if result:isOk() then
print(result:unwrapOk()) -- 1, 2, 3
elseif result:isErr() then
warn(result:unwrapErr()) -- An error occurred
end

There are also several other methods for chaining, combining, and mapping futures, as well as other utilities for working with futures.

It is suggested to read the API Documentation for more information about these methods.