0

我有一个Vapor 3项目可以上传一些格式为html. 并具有将此内容加载为html页面的功能。代码如下所示:

func newpost(_ reqest: Request) throws -> Future<View> {
    self.getContent(req: reqest) { (content) in
        return try reqest.view().render("newpost.leaf", content)
    }

}

func getContent(req:Request, callback: @escaping (String) -> ()) {
   let _ = BlogModel.query(on: req).first().map(to: BlogModel.self) { (blog) -> (BlogModel) in
        callback((blog?.content)!)
        return blog!
    }
}

但是这段代码会导致错误:

从 '(_) throws -> _' 类型的抛出函数到非抛出函数类型 '(String) -> ()' 的无效转换

如果我尝试return try reqest.view().render("newpost.leaf", content)使用该块的站点,那么我将无法获得content. 请帮助我以正确的方式加载它。

4

1 回答 1

0

您应该查看文档中的Async 部分(Promises 等)。无需使用回调。

这可能是从数据库获取数据并使用 Leaf 渲染它的一种方法(这与您的代码相同,但用 Promises 替换回调并清理不必要的代码):

enum APIError: AbortError {
    case dataNotFound
}

/// Render the HTML string using Leaf
func newPost(_ req: Request) throws -> Future<View> {
    return getContent(req)
        .flatMap(to: View.self) { model in
            // By default, Leaf will assume all templates have the "leaf" extension
            // There's no need to specify it
            return req.view().render("newpost", model)
        }
}

/// Retrieve X content from the DB
private func getContent(_ req: Request) throws -> Future<BlogModel> {
    return BlogModel.query(on: req)
        .first() // can be nil
        .unwrap(or: APIError.dataNotFound)
        // returns an unwrapped value or throws if none
}

如果您不想在找不到数据时抛出,例如,您可以使用 nil-coalescing 将 nil 转换为空字符串。

于 2018-05-01T21:56:40.240 回答