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
catchis 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)withself:try({ exec, catch })for safe error handling
Parameters
| Type | Name | Description |
|---|---|---|
function | exec | Function executed post promise initialization |
table | options | Options containing the following fields: • async (bool) - whether to execute asynchronously• timeout (number) - timeout duration in milliseconds |
Returns
| Type | Name | Description |
|---|---|---|
promise / bool | ctx | 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 argumentsor false on failure |
Callback: exec
exec([self], resolve, reject)| Type | Name | Description |
|---|---|---|
thread | self | Running thread instance incase options.async was enabled |
function | resolve | Callable function to resolve the promise with passed arguments |
function | reject | Callable function to reject the promise with passed arguments |
Examples
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)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)