async/await Basics
async/await lets your code pause while waiting for something slow, without freezing everything else, and then pick back up right where it left off.
Declaring an async Function
Adding async after a function's parameter list marks it as asynchronous, allowing it to use await internally and requiring callers to await it too.
Example: Declaring an async Function
func fetchGreeting() async -> String {
return "Hello from an async function"
}
let message = await fetchGreeting()
print(message)
Login to try C/C++/Java/PHP code in the editor
Awaiting Multiple async Calls in Sequence
Multiple await expressions run one after another in the order written, each suspending until its result is ready before moving to the next line.
Example: Awaiting Multiple async Calls in Sequence
func fetchNumber() async -> Int {
return 21
}
let first = await fetchNumber()
let second = await fetchNumber()
print("Sum: \(first + second)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Calling an
asyncfunction without theawaitkeyword; every call to an async function must be awaited. - Forgetting a function must be marked
asyncin its own signature before it's allowed toawaitother async calls inside it. - Assuming
awaitblocks the entire program; it only suspends the current task, letting other work proceed.
Chapter Summary
- A function marked
asynccan suspend and later resume without blocking the thread. - Calling an
asyncfunction requires theawaitkeyword at the call site. awaitmarks a potential suspension point where the function may pause.- async/await replaces older completion-handler-based asynchronous code with linear, readable syntax.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: