.\" Made by website/plain/build.mjs from website/words/await.md; change that file. .TH SG-AWAIT 7 2026-11-28 "SG" "SG reference" .SH NAME await \- waits for a task in an async function, without holding the thread, and gives what it returned .SH SYNOPSIS .TP \fBawait f(x)\fR runs the async function f as part of this task, and gives what it returns .TP \fBawait t\fR waits for the task t and takes it .TP \fB_ = await t\fR waits, and drops what it gave on purpose .TP \fBtry await t\fR waits, and passes an error on .TP \fBawait Task.whenAll(tasks)\fR waits for every task of a list .TP \fBawait Task.whenAny(ref tasks)\fR takes the first task of a list to end .TP \fBawait Task.delay(ms)\fR waits so many milliseconds .TP \fBawait select { ... }\fR waits on several channels .TP \fBawait lock v as x when c { ... }\fR waits until a condition on a locked value holds .SH DESCRIPTION \fBawait\fR waits for a task and gives what the task returned. It is written only in an async function, and it does not hold the thread meanwhile: the thread runs other tasks until this one can go on. Code that is not async waits with \fBt.wait()\fR instead. .PP \fBawait f(x)\fR runs \fBf\fR as part of the task that awaits it, with no task of its own, so \fBf\fR may borrow: \fBawait total(read numbers)\fR\&. \fBawait t\fR takes the task kept in \fBt\fR, which cannot be awaited again. What it gives is used, or dropped with \fB_ =\fR; a \fBTask\fR gives nothing to drop. .PP \fBawait\fR is an expression. It may stand in an argument, an operand, the condition of an \fBif\fR or a \fBwhile\fR, or the value of a \fBmatch\fR\&. The compiled program does not take it yet on a side that runs only sometimes, the right of \fB??\fR: give the value a name first. .PP A \fBlock\fR block never waits, so there is no \fBawait\fR inside one. .SH EXAMPLES .SS "Waiting for a call" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } async void main() { var answer = await twice(21) print(answer) _ = await twice(0) await Task.delay(5) print("done") } .fi .RE .PP .RS 4 .nf 42 done .fi .RE .PP \fB_ =\fR says the value of the second call is not needed. \fBTask.delay\fR gives a \fBTask\fR, so it needs no \fB_ =\fR\&. .SS "A call that borrows" .RS 4 .nf async int total(read List numbers) { await Task.delay(5) var sum = 0 for n in numbers { sum += n } return sum } async void main() { var numbers = List { 1, 2, 3, 4 } print(await total(read numbers)) numbers.add(5) print(await total(read numbers)) } .fi .RE .PP .RS 4 .nf 10 15 .fi .RE .PP The awaited call ends before \fBmain\fR goes on, so the borrow of \fBnumbers\fR ends with it, and \fBnumbers\fR can be changed on the next line. .SS "Inside an expression" .RS 4 .nf async int price(string item) { await Task.delay(20) return (int)item.length() * 10 } async bool inStock(string item) { await Task.delay(10) return item != "kite" } async void main() { var total = await price("tea") + await price("bread") print(total) if await inStock("kite") { print("kites are in") } else { print("no kites") } print(await price("milk") > 30) } .fi .RE .PP .RS 4 .nf 80 no kites true .fi .RE .PP Each \fBawait\fR is an operand, a condition or an argument like any other value. .SS "With try and ??" .RS 4 .nf async Result parseLater(string text) { await Task.delay(5) if int.parse(read text) is Ok(n) { return Ok(n) } return Error($"not a number: {text}".toString()) } async Result sum(string a, string b) { var x = try await parseLater(a) var y = try await parseLater(b) return Ok(x + y) } async void main() { match await sum("20", "22") { Ok(total) => print(total) Error(e) => print(e) } match await sum("20", "two") { Ok(total) => print(total) Error(e) => print(e) } var n = await parseLater("seven") ?? 7 print(n) } .fi .RE .PP .RS 4 .nf 42 not a number: two 7 .fi .RE .PP \fBtry await\fR waits, then passes an error on. \fBawait parseLater("seven") ?? 7\fR waits first, then takes \fB7\fR in place of the error. .SS "Several tasks at once" .RS 4 .nf async int fetch(string name, int ms) { await Task.delay(ms) return (int)name.length() } async void main() { var all = List>() all.add(fetch("north", 30)) all.add(fetch("south-east", 10)) all.add(fetch("west", 20)) print(await Task.whenAll(all)) var race = List>() race.add(fetch("slow", 300)) race.add(fetch("quick", 10)) while race.length() > 0 { print(await Task.whenAny(ref race)) } } .fi .RE .PP .RS 4 .nf [5, 10, 4] 5 4 .fi .RE .PP \fBTask.whenAll\fR gives what each task gave, in the order of the list, whichever ended first. \fBTask.whenAny\fR takes the first task to end out of the list, so the loop empties it: \fBquick\fR comes before \fBslow\fR\&. .SS "A wait cut short" .RS 4 .nf async void main() { var limit = CancellationSource.after(20) var token = limit.token() match await Task.delay(1000, read token) { Ok => print("waited the whole second") Error(cause) => print($"cut short: {cause}") } } .fi .RE .PP .RS 4 .nf cut short: Cancelled .fi .RE .PP Given a token, the delay gives a \fBResult\fR: \fBOk\fR when it waited its time, \fBError(Cancelled { })\fR when the token was cancelled first. .SS "Waiting on several channels" .RS 4 .nf async void produce(Sender out, int from, int to) { for i in from..to { _ = await out.sendAsync(i) } } async void main() { var small = Channel(4) var large = Channel(4) var a = produce(small.sender(), 1, 6) var b = produce(large.sender(), 100, 103) var total = 0 var items = 0 while true { await select { small.receive() as n => total += n large.receive() as n => total += n ended => break } items += 1 } await a await b print($"{items} items, {total} in all") } .fi .RE .PP .RS 4 .nf 8 items, 318 in all .fi .RE .PP In an async function, \fBselect\fR is written \fBawait select\fR, and a channel is sent to with \fBsendAsync\fR\&. \fBended\fR runs once both producers have ended and their channels are empty. .SS "Waiting for a locked value" .RS 4 .nf struct Box { List items bool done } async void fill(shared locked Box box) { for i in 1..4 { await Task.delay(5) lock box as b { b.items.add(i * 10) } } lock box as b { b.done = true } } async void main() { var box = new shared locked Box { items = List(), done = false } var filler = fill(share box) await lock box as b when b.done { print(b.items) } await filler } .fi .RE .PP .RS 4 .nf [10, 20, 30] .fi .RE .PP \fBawait lock ... when\fR lets the lock go and waits until \fBb.done\fR holds, then runs the block under the lock. The block itself waits for nothing. .SS "await on the right of ??" The file fallback/main.sg: .PP .RS 4 .nf async int fallback() { await Task.delay(5) return 7 } async void main() { int? cached = null var n = cached ?? await fallback() print(n) } .fi .RE .PP .RS 4 .nf $ cd fallback $ sg main.sg 7 $ sg build main.sg -o fallback $ ./fallback 7 .fi .RE .PP The right of \fB??\fR runs, and waits, only when the left has no value: compiled code puts it in an \fBif\fR of its own before the statement, as on the right of \fB&&\fR and \fB||\fR\&. Inside a larger expression that is not computed first, such as \fBif (c ?? await name()) == "s7"\fR with a text, the build says why it refuses it there, that the right of \fB??\fR runs only sometimes, and the hint is to give the value a name first. .SH "WHAT STOPS THE PROGRAM" .SS "A negative delay" .RS 4 .nf async int pause(int ms) { await Task.delay(ms) return ms } async void main() { print(await pause(10)) print(await pause(10 - 20)) } .fi .RE .PP .RS 4 .nf 10 panic: `Task.delay(-10)`: a delay is not negative --> example.sg:2:11 2 | await Task.delay(ms) | ^^^^^^^^^^^^^^ .fi .RE .SH "WHAT THE COMPILER REFUSES" .SS "await outside an async function" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } void main() { var x = await twice(2) print(x) } .fi .RE .PP .RS 4 .nf error: `await` is written in an async function --> example.sg:7:13 7 | var x = await twice(2) | ^^^^^^^^^^^^^^ hint: make `main` async (`async` in front of it), or wait for the task here: `twice(2).wait()` .fi .RE .SS "A value that is not a task" .RS 4 .nf async void main() { var n = await 5 print(n) } .fi .RE .PP .RS 4 .nf error: `await` waits for a task, and this is an `int` --> example.sg:2:19 2 | var n = await 5 | ^ .fi .RE .SS "A value left unused" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } async void main() { await twice(2) } .fi .RE .PP .RS 4 .nf error: the `int` that `await twice(2)` gives is not used --> example.sg:7:5 7 | await twice(2) | ^^^^^^^^^^^^^^ hint: keep it: `var value = await twice(2)`; to drop it on purpose, `_ = await twice(2)` .fi .RE .SS "A task awaited twice" .RS 4 .nf async int twice(int n) { await Task.delay(10) return n * 2 } async void main() { var task = twice(2) print(await task) print(await task) } .fi .RE .PP .RS 4 .nf error: `task` was moved and can no longer be used --> example.sg:9:17 9 | print(await task) | ^^^^ it was moved here: --> example.sg:8:17 8 | print(await task) | ^^^^ .fi .RE .PP \fBawait\fR takes the task. What it gave is kept in a variable when it is needed twice. .SS "await in a lock block" .RS 4 .nf async void main() { var counter = new shared locked 0 lock counter as c { await Task.delay(10) c += 1 } } .fi .RE .PP .RS 4 .nf error: a `lock` block does not await a task a task that holds a lock never waits, so it always lets the lock go: locks and waits cannot deadlock --> example.sg:4:9 4 | await Task.delay(10) | ^^^^^^^^^^^^^^^^^^^^ hint: await the task before the block or after it .fi .RE .SH "SEE ALSO" .BR sg-async (7), .BR sg-lock (7) .PP https://sg\-lang.org/reference/await.html