Home > Blockchain >  How to do async with Swift AWS Lambda Runtime
How to do async with Swift AWS Lambda Runtime

Time:09-13

I'm somewhat confused how to do async calls with the Swift AWS Lambda Runtime.

Here's an example of what I'm trying to do. This gives an error, because I'm trying to use await in the Lambda run closure.

// Request, uses Codable for transparent JSON encoding
private struct Request: Codable {
    let name: String
}

// Response, uses Codable for transparent JSON encoding
private struct Response: Codable {
    let message: String
}

private func sendResponse(request: Request) async -> Response {
    return Response(message: "Hello, \(request.name)")
}

// In this example we are receiving and responding with `Codable`.
Lambda.run { (context, request: Request, callback: @escaping (Result<Response, Error>) -> Void) in
    callback(.success(await sendResponse(request: request)))
}

Basically, I want to fetch some data using the AsyncHTTPClient package and return the response to the Lambda.

CodePudding user response:

Looks like you're running into trouble because you're trying to call await in a context that doesn't support concurrency.

One way to fix that is to use a Task. So you should be able to write something like:

Lambda.run { (context, request: Request, callback: @escaping (Result<Response, Error>) -> Void) in
    Task {
        let response = await sendResponse(request: request)
        callback(.success(response))
    }
}
  • Related