0

我有两个对象书签,书签,我想将对象作为参数传递给 Scala 模板,例如

return ok(views.html.bookmarks.list.render(bookmark, bookmarks));

在 F.Promise 中,

public static F.Promise<Result> get(final String id) {
    F.Promise<Bookmark> bookmark = Bookmark.findById(id);
    F.Promise<Collection<Bookmark>> bookmarks = Bookmark.findAll();
    // here how to write the code that should pass both objects to scala template
}

如何编写return语句以在没有Json Result的情况下在F.Promise中传递这两个对象?

4

2 回答 2

1

您需要映射未来的结果,如果您想从中传递 2 个对象,您可以使用Tuple。您还可以通过与zip同时进行数据库调用来改进这一点。当您使用时,zip()您将提高代码的效率并自动摆脱Tuple它。

public static F.Promise<Result> get(final String id) {
    return F.Promise.promise(() -> Bookmark.findById(id))
                    .zip(F.Promise.promise(Bookmark::findAll)) // results in a Tuple<Bookmark, Collection<Bookmark>>
                    .map(tuple -> ok(views.html.bookmarks.list.render(tuple._1, tuple._2)))
}

这不考虑错误处理,即id不存在的书签。为此,您需要查看recoveror recoverWith

于 2015-05-07T07:05:18.383 回答
0
   public static F.Promise<Result> index(Long id) {
F.Promise<Bookmark> futureBookmark = Bookmark.findById(id);
F.Promise<Collection<Bookmark>> futureBookmarks = Bookmark.findAll();
return futureBookmark.flatMap(new F.Function<Bookmark, F.Promise<Result>>() {
    @Override
    public F.Promise<Result> apply(final Bookmark bookmark) throws Throwable {
        return futureBookmarks.map(new F.Function<Collection<Bookmark>, Result>() {
            @Override
            public Result apply(Collection<Bookmark> bookmarks) throws Throwable {
                return ok(views.html.bookmarks.list.render(bookmark, bookmarks));
            }
        });
    }
});

}

对于 Java 1.7

于 2015-05-14T10:58:12.897 回答