【问题标题】:Cannot convert return expression of type 'EventLoopFuture<String>' to return type 'String'无法将类型“EventLoopF​​uture<String>”的返回表达式转换为返回类型“String”
【发布时间】:2021-09-30 07:43:19
【问题描述】:

我的 Vapor 项目中有这个错误:

无法将“EventLoopF​​uture”类型的返回表达式转换为“String”类型的返回

app.get("user", ":uuid") { req throws -> EventLoopFuture<String> in
        let uuid = req.parameters.get("uuid") ?? ""
        return User.query(on: req.db).filter(\.$uuid == uuid).first().flatMapThrowing { user in
            if let user = user {
                // return a string value
                return try Response(data: ["user": user.makeDictionary()])
            }else {
                // not found, return all users
                // problem is: Cannot convert return expression of type 'EventLoopFuture<String>' to return type 'String'
                return User.query(on: req.db).all().map { $0.map { $0.makeDictionary() } }.flatMapThrowing { dicArray in
                    return try Response(data: ["users": dicArray])
                }
            }
        }
    }

我该如何解决?

【问题讨论】:

  • 您是否尝试将EventLoopFuture&lt;String&gt; 替换为EventLoopFuture&lt;Response&gt;
  • 我只是试试。但是解决不了。新错误:无法将“String”类型的返回表达式转换为“Response”类型,无法将“EventLoopF​​uture”类型的返回表达式转换为“Response”类型
  • 你只需要阅读关于 EventLoopF​​utures kirilltitov.com/en/blog/2019/futures的那篇好文章就可以了

标签: ios swift vapor


【解决方案1】:

您刚刚声明您将在将来返回 String,而您正在尝试返回 Response。而且您还必须将flatMapThrowing 替换为tryFlatMap

固定代码

app.get("user", ":uuid") { req throws -> EventLoopFuture<Response> in
    let uuid = req.parameters.get("uuid") ?? ""
    return User
        .query(on: req.db)
        .filter(\.$uuid == uuid)
        .first()
        // here you can't use flatMapThrowing
        // cause it doesn't support EventLoopFuture result
        .tryFlatMap { user -> EventLoopFuture<Response> in
            if let user = user {
                // here you wrap simple return with future
                // cause it is needed for tryFlatMap
                let response = try Response(data: ["user": user.makeDictionary()])
                return req.eventLoop.makeSucceededFuture(response)
            } else {
                // here you return future with User
                return User.query(on: req.db).all()
                    // then you transform it to future with dictionary
                    .map { $0.map { $0.makeDictionary() } }
                    // then you transform it to future with Response
                    .flatMapThrowing { dicArray in
                        return try Response(data: ["users": dicArray])
                    }
            }
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2021-01-18
    • 2019-05-24
    • 2023-03-12
    相关资源
    最近更新 更多