makeFuture(Try<T>&&)
authorJames Sedgwick <jsedgwick@fb.com>
Fri, 9 May 2014 22:37:42 +0000 (15:37 -0700)
committerDave Watson <davejwatson@fb.com>
Tue, 20 May 2014 19:53:58 +0000 (12:53 -0700)
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 <typename Result, typename Op, typename... Args>
Future<Result> wrapper(Op op, Args&&... args) {
// ... do some stuff before...
return op(std::forward<Args>(args)...).then([] (Try<Result>&& t) {
// ... do some stuff after...
return makeFuture<Result>(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
folly/wangle/Future.h

index e563b86b657bf134f8bfbb4e5b84353b8c64a6ef..8d8af26718359f9e9d290410791f242640eba08c 100644 (file)
@@ -275,6 +275,25 @@ makeFuture(E const& e) {
   return std::move(f);
 }
 
+template <class T>
+Future<T> makeFuture(Try<T>&& t) {
+  try {
+    return makeFuture<T>(std::move(t.value()));
+  } catch (...) {
+    return makeFuture<T>(std::current_exception());
+  }
+}
+
+template <>
+inline Future<void> makeFuture(Try<void>&& t) {
+  try {
+    t.throwIfFailed();
+    return makeFuture();
+  } catch (...) {
+    return makeFuture<void>(std::current_exception());
+  }
+}
+
 // when (variadic)
 
 template <typename... Fs>
@@ -303,8 +322,9 @@ whenAll(InputIterator first, InputIterator last)
     typename std::iterator_traits<InputIterator>::value_type::value_type T;
 
   auto n = std::distance(first, last);
-  if (n == 0)
-    return makeFuture<std::vector<Try<T>>>({});
+  if (n == 0) {
+    return makeFuture(std::vector<Try<T>>());
+  }
 
   auto ctx = new detail::WhenAllContext<T>();
 
index c1deb6add651c92bacf11796b9a1e275a25559ae..f20ef40965d6da4d42cabf0ba897bf909e12c0a7 100644 (file)
@@ -258,6 +258,10 @@ template <class T, class E>
 typename std::enable_if<std::is_base_of<std::exception, E>::value, Future<T>>::type
 makeFuture(E const& e);
 
+/** Make a Future out of a Try */
+template <class T>
+Future<T> makeFuture(Try<T>&& 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