Async

Unstable Doc Ahead

The following documentation is lacking in detail. Be sure to check back for updates, or jump in if you can add any addtional information.

Using an async process, you can run longer-term child processes within the client lifecycle, without blocking the main loop. An async object holds the client request (and connection) until the subprocess has finished.

cloud.async


Using Async

An async object needs a child process to run. This is represented by a function that gets passed to the async.start method. You can also pass additional arguments to the async.start as well.

It's generally a good idea to create an "enclosure", and pass that to the async object. This allows you to use items from the outer scope in the child process.

Example

-- child process
local mathRan = math.random
local child_proc = function()
  cloud.log(mathRan(100))
end

local async, err = cloud.async.start(child_proc)

...

Another way to pass resources is through the async.start arguments.

Example

-- child process
local child_proc = function(mathRan, log)
  log(mathRan(100))
end
local async, err = cloud.async.start(child_proc, math.random, cloud.log)

Did You Know?

It's generally a better practice to use enclosures when possible.


Start

.start

Creates and starts a new async process.

Signature

cloud.async.start(child_func[, arg[, ...]])

Parameters

Name Description Type Default Required
child_func The child process to run. function nil Y
arg Arguments, comma delimited to be passed to the child function. string nil N

Returns

An async object, or nil and an error message. The returned async object can be used with both async.wait and async.stop.

Example

-- Create child process
local child = function()
  cloud.log('did something')
  return
end

local async, err = cloud.async.start(child)
if not async then
  cloud.log(err)
end

return async

Stop

.stop

Stops a previously started async process.

Signature

cloud.async.stop( async_obj )

Parameters

Name Description Type Default Required
async_obj The async object returned from async.start. userdata nil Y

Returns

A success boolean, or nil and an error message.

Example

local success, err = cloud.async.stop( async_id )
if not success then
  cloud.log(err)
end

Wait

.wait

Waits for multiple async processes to finish.

Signature

cloud.async.wait( asyncs )

Parameters

Name Description Type Default Required
asyncs A table array of async objects. table nil Y

Returns

A result table array, or nil and an error message.

Example

-- Mixing enclosure and arguments

local math_random = math.random

local child_proc = function(log)
  log(math_random(100))
end

local a1, err1 = cloud.async.start(child_proc, cloud.log)
local a2, err2 = cloud.async.start(child_proc, cloud.log)

local asyncs = { a1, a2 }

local results, err = cloud.async.wait( asyncs )
if not results then
  cloud.log(err)
  return
end

return results