Vital.sandbox
Thread

thread:create_promise

Shared

Creates a new promise context


Syntax

local ctx = thread:create_promise(exec = false, options = false)

Requires execution within a try/catch block to handle exceptions.

Parameters

TypeNameDescription
functionexecFunction executed post promise initialization
tableoptionsOptions containing the following fields:
async (bool) - whether to execute asynchronously
timeout (number) - timeout duration in milliseconds

Returns

TypeNameDescription
promise / boolctxReturns promise context containing the following fields on successful execution:
resolve (function) - callable function to resolve the promise with passed arguments
reject (function) - callable function to reject the promise with passed arguments
or false on failure

Callback

exec([self], resolve, reject)
TypeNameDescription
threadselfRunning thread instance incase options.async was enabled
functionresolveCallable function to resolve the promise with passed arguments
functionrejectCallable function to reject the promise with passed arguments

Examples

--Promise awaited without error handling - will throw error if rejected
local promise = thread:create_promise()

local self = thread:create(function(self)
    local result = {self:await(promise)}
    engine.print("Promise resolved:", table.unpack(result))
end)

self:resume()
timer:create(function()
    promise.resolve("Task completed", 123)
    --promise.reject("Task failed", 456)  --This would cause an unhandled error
end, 5000, 1)
--Promise with try/catch - safely handles both resolve and reject cases
local promise = thread:create_promise()

local self = thread:create(function(self)
    self:try({
        exec = function(self)
            local result = {self:await(promise)}
            engine.print("Promise resolved:", table.unpack(result))
        end,

        catch = function(...)
            engine.print("Promise rejected:", ...)
        end   
    })
end)

self:resume()
timer:create(function()
    --promise.resolve("Task completed", 123)
    promise.reject("Task failed", 456)  --This will be caught and handled
end, 5000, 1)

On this page