SwiftPumpkin

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

awaitreturns / throwsCallsresume(with:)Callertry awaitContinuationBridges callbackLegacy APICompletion handler
calls or tellsreports backThe compiler guarantees an async function returns once. The continuation enforces it at the bridge.
  • Combine's Future is a one-shot promise. async functions return or throw exactly once. withCheckedThrowingContinuation bridges old callbacks.
PartOwnsLooks like
async functionReturns or throws exactly oncefunc send() async throws
ContinuationWrap a callback APIwithCheckedThrowingContinuation
FutureOne-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 workasync/await.
Streams of valuesAsyncSequence, or Combine where you need operators.
Legacy callback APIsWrap once in a checked continuation.

Compared

Future vs async/await vs AsyncSequence

Futureasync/awaitAsyncSequence
ValuesOneOneMany
CancellationCancel subscriptionTask cancellationCancel the consuming task
ErrorsFailure typethrowsthrows 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.

30-second answer

Explain Promises → async/await in 30 seconds.

SwiftAsked directly

How do you wrap a completion-handler API with async/await, and which rule must never be broken?

SwiftAsked indirectly

Profiling shows checked continuations in a hot path. Can you switch to unsafe ones, and what do you give up?

iOS codingAsked indirectly

A UIKit button handler must call an async method and show errors. How do you bridge sync and async?

Read it in the app's source

Done with Promises → async/await? Mark it complete. Nailing its cards builds this pumpkin, row by row.