17 of 20 · Callbacks and concurrency
Promises → async/await
Futures and promises turn "call me back" into a value that represents a result arriving later. Swift's async/await makes that part of the language: an async function suspends, then returns or throws exactly once.
How it's wired
- Combine's Future is a one-shot promise. async functions return or throw exactly once. withCheckedThrowingContinuation bridges old callbacks.
| Part | Owns | Looks like |
|---|---|---|
| async function | Returns or throws exactly once | func send() async throws |
| Continuation | Wrap a callback API | withCheckedThrowingContinuation |
| Future | One-shot value object (Combine) | Future<Output, Failure> |
Swift example: forwarding Task cancellation + structured async let
Cancelling a Swift Task does not automatically cancel a wrapped callback API unless you wire withTaskCancellationHandler.
Cooperative cancellation bridge + parallel structured fetch
withTaskCancellationHandler cancels the underlying URLSessionTask immediately; async let auto-cancels sibling fetches if one throws.
// ✅ Forward Swift Task cancellation to an underlying callback-based request.
func downloadData(from url: URL, session: URLSession) async throws -> Data {
let box = TaskBox() // thread-safe holder for URLSessionDataTask
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
let task = session.dataTask(with: url) { data, _, error in
if let error { continuation.resume(throwing: error) }
else { continuation.resume(returning: data ?? Data()) }
}
box.set(task)
task.resume()
}
} onCancel: {
box.cancel() // stops network transfer instead of leaking bandwidth
}
}
// ✅ Structured parallelism: if either call throws, the sibling is cancelled automatically.
func loadDashboard(userID: String) async throws -> (Profile, [ThankYouNote]) {
async let profile = api.fetchProfile(userID)
async let notes = api.fetchNotes(userID)
return try await (profile, notes)
}Prefer URLSession.shared.data(from:) when available; use this bridge pattern for legacy or third-party callback SDKs.
What staff engineers watch for
- Bridging: wrap callback APIs with withCheckedThrowingContinuation. It traps on a double resume and logs if never resumed. Unsafe continuations remove those checks.
- Cancellation is cooperative. Cancelling a Task doesn't stop the callback API underneath; use withTaskCancellationHandler to cancel the real work.
- Task {} is unstructured: no automatic cancellation, and it inherits the current actor. Prefer async let and task groups, and .task in SwiftUI so work dies with the view.
- Actor reentrancy: across an await inside an actor, state can change. Re-check invariants after every suspension point.
What I'd use
| New one-shot async work | async/await. |
|---|---|
| Streams of values | AsyncSequence, or Combine where you need operators. |
| Legacy callback APIs | Wrap once in a checked continuation. |
Compared
Future vs async/await vs AsyncSequence
| Future | async/await | AsyncSequence | |
|---|---|---|---|
| Values | One | One | Many |
| Cancellation | Cancel subscription | Task cancellation | Cancel the consuming task |
| Errors | Failure type | throws | throws per element |
Expert notes
- Structured concurrency is the point: work that can't outlive its scope can't leak.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Promises → async/await in 30 seconds.
- Promises turned a callback into a value you could chain. async/await moved that into the language: an async function suspends, then returns or throws exactly once, and the compiler checks every path.
- I bridge each legacy callback API once, at the boundary, with
withCheckedThrowingContinuation. - A double resume then traps in any build, instead of silently doing the work twice.
- The risks that remain are cancellation, which is cooperative, and unstructured
Task {}work that outlives its screen.
How do you wrap a completion-handler API with async/await, and which rule must never be broken?
- Use
withCheckedThrowingContinuation, call the old API inside, and resume from its callback. - The rule is that every path resumes exactly once.
- A checked continuation traps on a double resume in every build and logs a warning if it's dropped.
- The unsafe version turns a double resume into undefined behavior and a dropped one into a silently leaked task.
Profiling shows checked continuations in a hot path. Can you switch to unsafe ones, and what do you give up?
- Yes, the APIs are identical, so it's a one-word swap.
- Only do it after the wrapper is verified and profiling proves it matters. You lose the safety net.
- A double resume becomes undefined behavior instead of a trap, and a dropped continuation silently leaks the task.
- Make sure tests cover every callback path before you swap.
A UIKit button handler must call an async method and show errors. How do you bridge sync and async?
- I'd start a
Taskin the handler. - Because the handler is on the main actor, the task inherits it, so after each
awaitI can update UI directly and catch errors in a normaldo/catch. - The task captures
selfuntil it finishes, which is fine for a quick save. - For longer work I'd store the handle and cancel it when the screen goes away or the work is superseded.
- I'd also disable the button, so a double tap can't start two saves.
- When several handlers need this, the task belongs in the view model.
Read it in the app's source
Done with Promises → async/await? Mark it complete. Nailing its cards builds this pumpkin, row by row.