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
| 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 | Returns 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([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
--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)