Vital.sandbox
Thread

thread:create_promise

Shared

Creates a new promise context


Syntax

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

Rejections that are not caught will throw a runtime error. It is strongly recommended to wrap promise resolution in a try/catch block.

  • Unhandled rejection — if the promise is rejected and no catch is present, an unhandled error will be thrown
  • With try/catch — both resolved and rejected outcomes are safely handled without interrupting execution
  • Recommended usage — always pair self:await(promise) with self:try({ exec, catch }) for safe error handling

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 / boolctxPromise 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

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

Await a promise without error handling
local promise = thread:create_promise()

local self = thread:create(function(self)
    local result = {self:await(promise)}
    engine.print("info", "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)
Await a promise with try/catch for safe rejection handling
local promise = thread:create_promise()

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

        catch = function(...)
            engine.print("info", "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