async let, Task, cancellation
Run work in parallel with async let , create independent Task s, and handle cancellation cooperatively.
What we cover
You will:
- Start sibling work with async let
- Launch independent units via Task { }
- Respond to cancellation using cooperative checks
async let basics
async let starts child tasks in parallel inside the same scope; you must await before leaving the scope.
func loadA() async -> Int { try? await Task.sleep(nanoseconds: 200_000_000); return 1 }
func loadB() async -> Int { try? await Task.sleep(nanoseconds: 200_000_000); return 2 }
Task {
async let a = loadA()
async let b = loadB()
// Both start immediately; awaiting joins them
let sum = await (a + b)
print("sum =", sum) // 3
}All lessons in this course
- Structured concurrency, async functions
- async let, Task, cancellation
- try await and error propagation