2 * Copyright 2017-present Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include <folly/futures/Future.h>
22 template <typename ExecutorImpl>
23 class FutureExecutor : public ExecutorImpl {
25 template <typename... Args>
26 explicit FutureExecutor(Args&&... args)
27 : ExecutorImpl(std::forward<Args>(args)...) {}
30 * Given a function func that returns a Future<T>, adds that function to the
31 * contained Executor and returns a Future<T> which will be fulfilled with
32 * func's result once it has been executed.
34 * For example: auto f = futureExecutor.addFuture([](){
35 * return doAsyncWorkAndReturnAFuture();
39 typename std::enable_if<
40 folly::isFuture<typename std::result_of<F()>::type>::value,
41 typename std::result_of<F()>::type>::type
43 typedef typename std::result_of<F()>::type::value_type T;
44 folly::Promise<T> promise;
45 auto future = promise.getFuture();
47 [ promise = std::move(promise), func = std::move(func) ]() mutable {
48 func().then([promise = std::move(promise)](
49 folly::Try<T> && t) mutable { promise.setTry(std::move(t)); });
55 * Similar to addFuture above, but takes a func that returns some non-Future
58 * For example: auto f = futureExecutor.addFuture([]() {
63 typename std::enable_if<
64 !folly::isFuture<typename std::result_of<F()>::type>::value,
65 folly::Future<typename folly::Unit::Lift<
66 typename std::result_of<F()>::type>::type>>::type
69 typename folly::Unit::Lift<typename std::result_of<F()>::type>::type;
70 folly::Promise<T> promise;
71 auto future = promise.getFuture();
73 [ promise = std::move(promise), func = std::move(func) ]() mutable {
74 promise.setWith(std::move(func));