swift Steam : catchMap not being awaited

标签 swift future vapor

我在 Controller 中有以下代码部分,它查询 MailGun 发送电子邮件,然后最好在返回 Controller 之前等待响应。按照现在的配置,此应该会失败,因为我故意破坏了 MailGun 配置。但目前 Controller 正在返回成功状态,因为 .catchMap 功能没有得到正确等待,并且我不确定如何正确构建我的代码以使其正确。

return emailTemplate.render(emailData, on: req).map { message -> Future<Response> in
    let deliveryService = try req.make(EmailDeliveryService.self)
    return try deliveryService.send(message, on: req)
}.catchMap { error in
    /// this is not being awaited, and no abort is thrown before the request returns
    throw Abort(.internalServerError, reason: "Error sending email.")
}.transform(to: savedObj)

应该正确等待的函数,deliverService.send,具有方法签名:

func send(_ message: EmailMessage, on container: Container) throws -> Future<Response>

如何正确构造此代码以正确捕获 deliveryService.send 方法结果返回的错误?

最佳答案

如果您的render()方法签名是这样的:

func render(…) -> Future<String>

那么,我认为你需要使用flatMap而不是map在:

return emailTemplate.render(emailData, on: req).map // <—

现在,catchMaptransform方法正在接收 Future<Future<Response>>因为map只转换给定 future 的封装数据,如下所示:

Future<String> -map(String -> Future<Response)-> Future<Future<Response>>

使用flatMap ,它将展平双 Future,这就是此方法的目的,导致:

Future<String> -flatMap(String -> Future<Response)-> Future<Response>

然后,catchMap将能够访问错误。

关于 swift Steam : catchMap not being awaited,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511297/

相关文章:

ios - DateFormatter 返回 nil 以及 TimeZone 和 Locale 的特定组合

swift - RxSwift,将Observable<[array]>分为Observable<a>,Observable<b>

mysql - swift Vapor - 操作无法完成。 (MySQL.Error 错误 4.)

Swift Vapor Postgres Xcode 构建错误 : Could not build Objective-C module 'CPostgreSQLMac'

swift - 使用不同的数据库提供商测试 Vapor 3

swift - 在应用程序扩展中找不到库中的 cocoapods

ios - 无法在 iPad 上打开 Playground Book

asynchronous - 如何接受异步函数作为参数?

scala - 如何处理 Scala Futures 中的异常?

flutter - 使用 Flutter 和 Dart,我怎样才能让这个 Future 工作?