23 · Concurrency
Reading an asynchronous source
`for await` asks the source for one value at a time and awaits `next()` before running the loop body.
On this page
for await asks the source for one value at a time and awaits next() before running the loop body. Nil ends the iteration. A known next() method must return Future<T?> or Task<T?>, and the source must implement core::cleanup::Cleanup. This example consumes a complete source and stops a second source early; both are closed.
Reading an asynchronous source.
use core::cleanup::Cleanup
struct Events { remaining: int }
impl Events {
async fn next(self) -> int? {
if self.remaining <= 0 { return nil }
let value = self.remaining
self.remaining -= 1
return value
}
}
impl Cleanup for Events {
fn close(self) { print("closed") }
}
let complete = Events { remaining: 3 }
var sum = 0
for await value in complete { sum += value }
assert_eq(sum, 6)
let early = Events { remaining: 5 }
:events for await value in early {
if value == 4 { break :events }
print(value)
}
print(sum)
The source is acquired once and closed on completion, break, return, failure or cooperative cancellation. Pattern bindings, including for await case, apply to the awaited value. Synchronous arrays do not become asynchronous sources. Run this example with the CLI; wasm-aot rejects scheduler operations explicitly.
See also