Function
await
Waits for a result inside an async task. It takes two forms. The first is a starter function: it receives resume and starts something that ends in a callback (a dbQuery query, fetchRemote, a timer). When the callback calls resume(...), await returns the same values. The second form is another task from async: await waits until it ends and returns its results, and if that task failed, it re-throws the error (catch it with pcall).
Syntax
var await(function, task starter [, var ...])Arguments
starterfunction, task- A
function(resume, ...)function or a task fromasync. ...var, optional = nil- Extra arguments passed to the starter after
resume.
Returns
The values passed to resume or the task's results.
Example
local db = dbConnect("sqlite", "gracze.db")
addCommandHandler("pieniadze", function(player)
async(function()
local qh = await(function(resume)
dbQuery(resume, db, "SELECT money FROM gracze WHERE nick = ?", getPlayerName(player))
end)
local rows = dbPoll(qh, 0)
local money = rows and rows[1] and rows[1].money or 0
outputChatBox("Masz $" .. money, player)
end)
end)
Notes
Only inside a task. Outside async it raises only allowed inside async. Further calls to the same resume are ignored, and calling resume right away inside the starter works too.
See also
asyncRuns a function as a task (coroutine). The code in the task runs immediately until its first wait (sleep,await,waitForEvent). Then it yields and the server and the game keep running. When the wait is over, the task continues from where it stopped. This lets you write steps spread over time (a countdown, a database query, an HTTP response, waiting for a player) one after another, without nested callbacks and timers.sleepPauses anasynctask for the given time. Meanwhile other scripts, the server and the game run normally.sleep(0)waits until the next server frame (the same assetTimerwith interval 0).waitForEventPauses anasynctask until an event happens. Returns the event'ssourceelement and its arguments. With a time limit it returnsfalseif the event did not happen in time. The handler and the limit timer are removed when the wait ends.