From 74ff76d8eafb6cd2d1d82d2d9061788f14e3c6f2 Mon Sep 17 00:00:00 2001 From: James Sedgwick Date: Fri, 9 May 2014 15:37:42 -0700 Subject: [PATCH] makeFuture(Try&&) Summary: @override-unit-failures Add makeFuture variant which extracts the result contained in a Try and sticks it in a Future One use case: ``` template Future wrapper(Op op, Args&&... args) { // ... do some stuff before... return op(std::forward(args)...).then([] (Try&& t) { // ... do some stuff after... return makeFuture(std::move(t)); }); } ``` With this makeFuture variant, "wrapper" doesn't need to be specialized for when Result is void Test Plan: employed in my code, will link to diff when ready Reviewed By: hans@fb.com FB internal diff: D1318047 --- folly/wangle/Future-inl.h | 24 ++++++++++++++++++++++-- folly/wangle/Future.h | 4 ++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/folly/wangle/Future-inl.h b/folly/wangle/Future-inl.h index e563b86b..8d8af267 100644 --- a/folly/wangle/Future-inl.h +++ b/folly/wangle/Future-inl.h @@ -275,6 +275,25 @@ makeFuture(E const& e) { return std::move(f); } +template +Future makeFuture(Try&& t) { + try { + return makeFuture(std::move(t.value())); + } catch (...) { + return makeFuture(std::current_exception()); + } +} + +template <> +inline Future makeFuture(Try&& t) { + try { + t.throwIfFailed(); + return makeFuture(); + } catch (...) { + return makeFuture(std::current_exception()); + } +} + // when (variadic) template @@ -303,8 +322,9 @@ whenAll(InputIterator first, InputIterator last) typename std::iterator_traits::value_type::value_type T; auto n = std::distance(first, last); - if (n == 0) - return makeFuture>>({}); + if (n == 0) { + return makeFuture(std::vector>()); + } auto ctx = new detail::WhenAllContext(); diff --git a/folly/wangle/Future.h b/folly/wangle/Future.h index c1deb6ad..f20ef409 100644 --- a/folly/wangle/Future.h +++ b/folly/wangle/Future.h @@ -258,6 +258,10 @@ template typename std::enable_if::value, Future>::type makeFuture(E const& e); +/** Make a Future out of a Try */ +template +Future makeFuture(Try&& t); + /** When all the input Futures complete, the returned Future will complete. Errors do not cause early termination; this Future will always succeed after all its Futures have finished (whether successfully or with an -- 2.34.1