Using guard with async let x =

I have code that’s like this…

func fetchLotsOfThings(eventData: EventData, req: Request) async throws -> Response {
    async let event = Event.find(eventData.id, on: req.db)
    async let group = InterestGroup.find(eventData.groupID, on: req.db)
    async let venue = Venue.find(eventData.venueID, on: req.db)

    guard let event = try await event,
        let group = try await group,
        let venue = try await venue else {
            throw Abort(.notFound)
    }
    return response(for: event, in: group, at: venue)
}

I feel like I’m not doing this properly. Is there a way to use the more concise guard let optional unwrapping with async let? Ex:

guard let try await event,
      let try await group,
      let try await venue else {
    throw Abort(.notFound)
}

Note - let event = try await eventlet try await event

These get compiler errors:

  • guard let event else {...}
  • guard let await event else {...}
  • guard let try await event else {...}

guard let try await someOptional else {...} would make async let variables have a parallel to the synchronous guard let someOptional else {...}

2 Likes

I like the realism of your question but prefer a simple reduction.

Here is the simplest thing that would be useful, to compile. Your use case would spring from it like a flower from well-tended humus.

var asyncSomething: (some Any)? {
  get async { () }
}

if let await asyncSomething { } // ❌