20a56b7e05aa612751979cc87f7a80b58a10eff1
[folly.git] / folly / futures / Future.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <algorithm>
20 #include <exception>
21 #include <functional>
22 #include <memory>
23 #include <type_traits>
24 #include <vector>
25
26 #include <folly/Optional.h>
27 #include <folly/Portability.h>
28 #include <folly/ScopeGuard.h>
29 #include <folly/Try.h>
30 #include <folly/Utility.h>
31 #include <folly/executors/DrivableExecutor.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/Promise.h>
34 #include <folly/futures/detail/Types.h>
35
36 // boring predeclarations and details
37 #include <folly/futures/Future-pre.h>
38
39 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
40 // Needs to be included after Future-pre.h and before Future-inl.h
41 #include <folly/futures/helpers.h>
42
43 namespace folly {
44
45 template <class T>
46 class Future;
47
48 template <class T>
49 class SemiFuture;
50
51 namespace futures {
52 namespace detail {
53 template <class T>
54 class FutureBase {
55  public:
56   typedef T value_type;
57
58   /// Construct a Future from a value (perfect forwarding)
59   template <
60       class T2 = T,
61       typename = typename std::enable_if<
62           !isFuture<typename std::decay<T2>::type>::value &&
63           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
64   /* implicit */ FutureBase(T2&& val);
65
66   template <class T2 = T>
67   /* implicit */ FutureBase(
68       typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
69
70   template <
71       class... Args,
72       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
73           type = 0>
74   explicit FutureBase(in_place_t, Args&&... args);
75
76   FutureBase(FutureBase<T> const&) = delete;
77   FutureBase(SemiFuture<T>&&) noexcept;
78   FutureBase(Future<T>&&) noexcept;
79
80   // not copyable
81   FutureBase(Future<T> const&) = delete;
82   FutureBase(SemiFuture<T> const&) = delete;
83
84   ~FutureBase();
85
86   /// Returns a reference to the result, with a reference category and const-
87   /// qualification equivalent to the reference category and const-qualification
88   /// of the receiver.
89   ///
90   /// If moved-from, throws NoState.
91   ///
92   /// If !isReady(), throws FutureNotReady.
93   ///
94   /// If an exception has been captured, throws that exception.
95   T& value() &;
96   T const& value() const&;
97   T&& value() &&;
98   T const&& value() const&&;
99
100   /** True when the result (or exception) is ready. */
101   bool isReady() const;
102
103   /// sugar for getTry().hasValue()
104   bool hasValue();
105
106   /// sugar for getTry().hasException()
107   bool hasException();
108
109   /// If the promise has been fulfilled, return an Optional with the Try<T>.
110   /// Otherwise return an empty Optional.
111   /// Note that this moves the Try<T> out.
112   Optional<Try<T>> poll();
113
114   /// This is not the method you're looking for.
115   ///
116   /// This needs to be public because it's used by make* and when*, and it's
117   /// not worth listing all those and their fancy template signatures as
118   /// friends. But it's not for public consumption.
119   template <class F>
120   void setCallback_(F&& func);
121
122   bool isActive() {
123     return core_->isActive();
124   }
125
126   template <class E>
127   void raise(E&& exception) {
128     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
129         std::forward<E>(exception)));
130   }
131
132   /// Raise an interrupt. If the promise holder has an interrupt
133   /// handler it will be called and potentially stop asynchronous work from
134   /// being done. This is advisory only - a promise holder may not set an
135   /// interrupt handler, or may do anything including ignore. But, if you know
136   /// your future supports this the most likely result is stopping or
137   /// preventing the asynchronous operation (if in time), and the promise
138   /// holder setting an exception on the future. (That may happen
139   /// asynchronously, of course.)
140   void raise(exception_wrapper interrupt);
141
142   void cancel() {
143     raise(FutureCancellation());
144   }
145
146  protected:
147   friend class Promise<T>;
148   template <class>
149   friend class SemiFuture;
150   template <class>
151   friend class Future;
152
153   using corePtr = futures::detail::Core<T>*;
154
155   // shared core state object
156   corePtr core_;
157
158   explicit FutureBase(corePtr obj) : core_(obj) {}
159
160   explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
161
162   void detach();
163
164   void throwIfInvalid() const;
165
166   template <class FutureType>
167   void assign(FutureType&) noexcept;
168
169   Executor* getExecutor() {
170     return core_->getExecutor();
171   }
172
173   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
174     core_->setExecutor(x, priority);
175   }
176
177   // Variant: returns a value
178   // e.g. f.then([](Try<T> t){ return t.value(); });
179   template <typename F, typename R, bool isTry, typename... Args>
180   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
181   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
182
183   // Variant: returns a Future
184   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
185   template <typename F, typename R, bool isTry, typename... Args>
186   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
187   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
188 };
189 } // namespace detail
190 } // namespace futures
191
192 template <class T>
193 class SemiFuture : private futures::detail::FutureBase<T> {
194  private:
195   using Base = futures::detail::FutureBase<T>;
196   using DeferredExecutor = futures::detail::DeferredExecutor;
197
198  public:
199   static SemiFuture<T> makeEmpty(); // equivalent to moved-from
200
201   // Export public interface of FutureBase
202   // FutureBase is inherited privately to avoid subclasses being cast to
203   // a FutureBase pointer
204   using typename Base::value_type;
205
206   /// Construct a Future from a value (perfect forwarding)
207   template <
208       class T2 = T,
209       typename = typename std::enable_if<
210           !isFuture<typename std::decay<T2>::type>::value &&
211           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
212   /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
213
214   template <class T2 = T>
215   /* implicit */ SemiFuture(
216       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
217       : Base(p) {}
218
219   template <
220       class... Args,
221       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
222           type = 0>
223   explicit SemiFuture(in_place_t, Args&&... args)
224       : Base(in_place, std::forward<Args>(args)...) {}
225
226   SemiFuture(SemiFuture<T> const&) = delete;
227   // movable
228   SemiFuture(SemiFuture<T>&&) noexcept;
229   // safe move-constructabilty from Future
230   /* implicit */ SemiFuture(Future<T>&&) noexcept;
231
232   using Base::cancel;
233   using Base::hasException;
234   using Base::hasValue;
235   using Base::isActive;
236   using Base::isReady;
237   using Base::poll;
238   using Base::raise;
239   using Base::setCallback_;
240   using Base::value;
241
242   SemiFuture& operator=(SemiFuture const&) = delete;
243   SemiFuture& operator=(SemiFuture&&) noexcept;
244   SemiFuture& operator=(Future<T>&&) noexcept;
245
246   /// Block until the future is fulfilled. Returns the value (moved out), or
247   /// throws the exception. The future must not already have a callback.
248   T get() &&;
249
250   /// Block until the future is fulfilled, or until timed out. Returns the
251   /// value (moved out), or throws the exception (which might be a TimedOut
252   /// exception).
253   T get(Duration dur) &&;
254
255   /// Block until the future is fulfilled, or until timed out. Returns the
256   /// Try of the value (moved out).
257   Try<T> getTry() &&;
258
259   /// Block until this Future is complete. Returns a reference to this Future.
260   SemiFuture<T>& wait() &;
261
262   /// Overload of wait() for rvalue Futures
263   SemiFuture<T>&& wait() &&;
264
265   /// Block until this Future is complete or until the given Duration passes.
266   /// Returns a reference to this Future
267   SemiFuture<T>& wait(Duration) &;
268
269   /// Overload of wait(Duration) for rvalue Futures
270   SemiFuture<T>&& wait(Duration) &&;
271
272   /// Returns an inactive Future which will call back on the other side of
273   /// executor (when it is activated).
274   ///
275   /// NB remember that Futures activate when they destruct. This is good,
276   /// it means that this will work:
277   ///
278   ///   f.via(e).then(a).then(b);
279   ///
280   /// a and b will execute in the same context (the far side of e), because
281   /// the Future (temporary variable) created by via(e) does not call back
282   /// until it destructs, which is after then(a) and then(b) have been wired
283   /// up.
284   ///
285   /// But this is still racy:
286   ///
287   ///   f = f.via(e).then(a);
288   ///   f.then(b);
289   // The ref-qualifier allows for `this` to be moved out so we
290   // don't get access-after-free situations in chaining.
291   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
292   inline Future<T> via(
293       Executor* executor,
294       int8_t priority = Executor::MID_PRI) &&;
295
296   /**
297    * Defer work to run on the consumer of the future.
298    * This work will be run eithe ron an executor that the caller sets on the
299    * SemiFuture, or inline with the call to .get().
300    * NB: This is a custom method because boost-blocking executors is a
301    * special-case for work deferral in folly. With more general boost-blocking
302    * support all executors would boost block and we would simply use some form
303    * of driveable executor here.
304    */
305   template <typename F>
306   SemiFuture<typename futures::detail::callableResult<T, F>::Return::value_type>
307   defer(F&& func) &&;
308
309   // Public as for setCallback_
310   // Ensure that a boostable executor performs work to chain deferred work
311   // cleanly
312   void boost_();
313
314  private:
315   friend class Promise<T>;
316   template <class>
317   friend class futures::detail::FutureBase;
318   template <class>
319   friend class SemiFuture;
320
321   using typename Base::corePtr;
322   using Base::setExecutor;
323   using Base::throwIfInvalid;
324
325   template <class T2>
326   friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
327
328   explicit SemiFuture(corePtr obj) : Base(obj) {}
329
330   explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
331       : Base(futures::detail::EmptyConstruct{}) {}
332 };
333
334 template <class T>
335 class Future : private futures::detail::FutureBase<T> {
336  private:
337   using Base = futures::detail::FutureBase<T>;
338
339  public:
340   // Export public interface of FutureBase
341   // FutureBase is inherited privately to avoid subclasses being cast to
342   // a FutureBase pointer
343   using typename Base::value_type;
344
345   /// Construct a Future from a value (perfect forwarding)
346   template <
347       class T2 = T,
348       typename = typename std::enable_if<
349           !isFuture<typename std::decay<T2>::type>::value &&
350           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
351   /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
352
353   template <class T2 = T>
354   /* implicit */ Future(
355       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
356       : Base(p) {}
357
358   template <
359       class... Args,
360       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
361           type = 0>
362   explicit Future(in_place_t, Args&&... args)
363       : Base(in_place, std::forward<Args>(args)...) {}
364
365   Future(Future<T> const&) = delete;
366   // movable
367   Future(Future<T>&&) noexcept;
368
369   // converting move
370   template <
371       class T2,
372       typename std::enable_if<
373           !std::is_same<T, typename std::decay<T2>::type>::value &&
374               std::is_constructible<T, T2&&>::value &&
375               std::is_convertible<T2&&, T>::value,
376           int>::type = 0>
377   /* implicit */ Future(Future<T2>&&);
378   template <
379       class T2,
380       typename std::enable_if<
381           !std::is_same<T, typename std::decay<T2>::type>::value &&
382               std::is_constructible<T, T2&&>::value &&
383               !std::is_convertible<T2&&, T>::value,
384           int>::type = 0>
385   explicit Future(Future<T2>&&);
386   template <
387       class T2,
388       typename std::enable_if<
389           !std::is_same<T, typename std::decay<T2>::type>::value &&
390               std::is_constructible<T, T2&&>::value,
391           int>::type = 0>
392   Future& operator=(Future<T2>&&);
393
394   using Base::cancel;
395   using Base::hasException;
396   using Base::hasValue;
397   using Base::isActive;
398   using Base::isReady;
399   using Base::poll;
400   using Base::raise;
401   using Base::setCallback_;
402   using Base::value;
403
404   static Future<T> makeEmpty(); // equivalent to moved-from
405
406   // not copyable
407   Future& operator=(Future const&) = delete;
408
409   // movable
410   Future& operator=(Future&&) noexcept;
411
412   /// Call e->drive() repeatedly until the future is fulfilled. Examples
413   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
414   /// reference to the Try of the value.
415   Try<T>& getTryVia(DrivableExecutor* e);
416
417   /// Call e->drive() repeatedly until the future is fulfilled. Examples
418   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
419   /// value (moved out), or throws the exception.
420   T getVia(DrivableExecutor* e);
421
422   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
423   /// Future<T> instance.
424   template <class F = T>
425   typename std::
426       enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
427       unwrap();
428
429   /// Returns an inactive Future which will call back on the other side of
430   /// executor (when it is activated).
431   ///
432   /// NB remember that Futures activate when they destruct. This is good,
433   /// it means that this will work:
434   ///
435   ///   f.via(e).then(a).then(b);
436   ///
437   /// a and b will execute in the same context (the far side of e), because
438   /// the Future (temporary variable) created by via(e) does not call back
439   /// until it destructs, which is after then(a) and then(b) have been wired
440   /// up.
441   ///
442   /// But this is still racy:
443   ///
444   ///   f = f.via(e).then(a);
445   ///   f.then(b);
446   // The ref-qualifier allows for `this` to be moved out so we
447   // don't get access-after-free situations in chaining.
448   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
449   inline Future<T> via(
450       Executor* executor,
451       int8_t priority = Executor::MID_PRI) &&;
452
453   /// This variant creates a new future, where the ref-qualifier && version
454   /// moves `this` out. This one is less efficient but avoids confusing users
455   /// when "return f.via(x);" fails.
456   inline Future<T> via(
457       Executor* executor,
458       int8_t priority = Executor::MID_PRI) &;
459
460   /** When this Future has completed, execute func which is a function that
461     takes one of:
462       (const) Try<T>&&
463       (const) Try<T>&
464       (const) Try<T>
465       (const) T&&
466       (const) T&
467       (const) T
468       (void)
469
470     Func shall return either another Future or a value.
471
472     A Future for the return type of func is returned.
473
474     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
475
476     The Future given to the functor is ready, and the functor may call
477     value(), which may rethrow if this has captured an exception. If func
478     throws, the exception will be captured in the Future that is returned.
479     */
480   template <typename F, typename R = futures::detail::callableResult<T, F>>
481   typename R::Return then(F&& func) {
482     return this->template thenImplementation<F, R>(
483         std::forward<F>(func), typename R::Arg());
484   }
485
486   /// Variant where func is an member function
487   ///
488   ///   struct Worker { R doWork(Try<T>); }
489   ///
490   ///   Worker *w;
491   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
492   ///
493   /// This is just sugar for
494   ///
495   ///   f1.then(std::bind(&Worker::doWork, w));
496   template <typename R, typename Caller, typename... Args>
497   Future<typename isFuture<R>::Inner> then(
498       R (Caller::*func)(Args...),
499       Caller* instance);
500
501   /// Execute the callback via the given Executor. The executor doesn't stick.
502   ///
503   /// Contrast
504   ///
505   ///   f.via(x).then(b).then(c)
506   ///
507   /// with
508   ///
509   ///   f.then(x, b).then(c)
510   ///
511   /// In the former both b and c execute via x. In the latter, only b executes
512   /// via x, and c executes via the same executor (if any) that f had.
513   template <class Executor, class Arg, class... Args>
514   auto then(Executor* x, Arg&& arg, Args&&... args) {
515     auto oldX = this->getExecutor();
516     this->setExecutor(x);
517     return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
518         .via(oldX);
519   }
520
521   /// Convenience method for ignoring the value and creating a Future<Unit>.
522   /// Exceptions still propagate.
523   /// This function is identical to .unit().
524   Future<Unit> then();
525
526   /// Convenience method for ignoring the value and creating a Future<Unit>.
527   /// Exceptions still propagate.
528   /// This function is identical to parameterless .then().
529   Future<Unit> unit() {
530     return then();
531   }
532
533   /// Set an error callback for this Future. The callback should take a single
534   /// argument of the type that you want to catch, and should return a value of
535   /// the same type as this Future, or a Future of that type (see overload
536   /// below). For instance,
537   ///
538   /// makeFuture()
539   ///   .then([] {
540   ///     throw std::runtime_error("oh no!");
541   ///     return 42;
542   ///   })
543   ///   .onError([] (std::runtime_error& e) {
544   ///     LOG(INFO) << "std::runtime_error: " << e.what();
545   ///     return -1; // or makeFuture<int>(-1)
546   ///   });
547   template <class F>
548   typename std::enable_if<
549       !futures::detail::callableWith<F, exception_wrapper>::value &&
550           !futures::detail::callableWith<F, exception_wrapper&>::value &&
551           !futures::detail::Extract<F>::ReturnsFuture::value,
552       Future<T>>::type
553   onError(F&& func);
554
555   /// Overload of onError where the error callback returns a Future<T>
556   template <class F>
557   typename std::enable_if<
558       !futures::detail::callableWith<F, exception_wrapper>::value &&
559           !futures::detail::callableWith<F, exception_wrapper&>::value &&
560           futures::detail::Extract<F>::ReturnsFuture::value,
561       Future<T>>::type
562   onError(F&& func);
563
564   /// Overload of onError that takes exception_wrapper and returns Future<T>
565   template <class F>
566   typename std::enable_if<
567       futures::detail::callableWith<F, exception_wrapper>::value &&
568           futures::detail::Extract<F>::ReturnsFuture::value,
569       Future<T>>::type
570   onError(F&& func);
571
572   /// Overload of onError that takes exception_wrapper and returns T
573   template <class F>
574   typename std::enable_if<
575       futures::detail::callableWith<F, exception_wrapper>::value &&
576           !futures::detail::Extract<F>::ReturnsFuture::value,
577       Future<T>>::type
578   onError(F&& func);
579
580   /// func is like std::function<void()> and is executed unconditionally, and
581   /// the value/exception is passed through to the resulting Future.
582   /// func shouldn't throw, but if it does it will be captured and propagated,
583   /// and discard any value/exception that this Future has obtained.
584   template <class F>
585   Future<T> ensure(F&& func);
586
587   /// Like onError, but for timeouts. example:
588   ///
589   ///   Future<int> f = makeFuture<int>(42)
590   ///     .delayed(long_time)
591   ///     .onTimeout(short_time,
592   ///       []() -> int{ return -1; });
593   ///
594   /// or perhaps
595   ///
596   ///   Future<int> f = makeFuture<int>(42)
597   ///     .delayed(long_time)
598   ///     .onTimeout(short_time,
599   ///       []() { return makeFuture<int>(some_exception); });
600   template <class F>
601   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
602
603   /// A Future's callback is executed when all three of these conditions have
604   /// become true: it has a value (set by the Promise), it has a callback (set
605   /// by then), and it is active (active by default).
606   ///
607   /// Inactive Futures will activate upon destruction.
608   FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
609     this->core_->activate();
610     return *this;
611   }
612   FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
613     this->core_->deactivate();
614     return *this;
615   }
616   FOLLY_DEPRECATED("do not use") Future<T> activate() && {
617     this->core_->activate();
618     return std::move(*this);
619   }
620   FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
621     this->core_->deactivate();
622     return std::move(*this);
623   }
624
625   /// Throw TimedOut if this Future does not complete within the given
626   /// duration from now. The optional Timeekeeper is as with futures::sleep().
627   Future<T> within(Duration, Timekeeper* = nullptr);
628
629   /// Throw the given exception if this Future does not complete within the
630   /// given duration from now. The optional Timeekeeper is as with
631   /// futures::sleep().
632   template <class E>
633   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
634
635   /// Delay the completion of this Future for at least this duration from
636   /// now. The optional Timekeeper is as with futures::sleep().
637   Future<T> delayed(Duration, Timekeeper* = nullptr);
638
639   /// Block until the future is fulfilled. Returns the value (moved out), or
640   /// throws the exception. The future must not already have a callback.
641   T get();
642
643   /// Block until the future is fulfilled, or until timed out. Returns the
644   /// value (moved out), or throws the exception (which might be a TimedOut
645   /// exception).
646   T get(Duration dur);
647
648   /** A reference to the Try of the value */
649   Try<T>& getTry();
650
651   /// Block until this Future is complete. Returns a reference to this Future.
652   Future<T>& wait() &;
653
654   /// Overload of wait() for rvalue Futures
655   Future<T>&& wait() &&;
656
657   /// Block until this Future is complete or until the given Duration passes.
658   /// Returns a reference to this Future
659   Future<T>& wait(Duration) &;
660
661   /// Overload of wait(Duration) for rvalue Futures
662   Future<T>&& wait(Duration) &&;
663
664   /// Call e->drive() repeatedly until the future is fulfilled. Examples
665   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
666   /// reference to this Future so that you can chain calls if desired.
667   /// value (moved out), or throws the exception.
668   Future<T>& waitVia(DrivableExecutor* e) &;
669
670   /// Overload of waitVia() for rvalue Futures
671   Future<T>&& waitVia(DrivableExecutor* e) &&;
672
673   /// If the value in this Future is equal to the given Future, when they have
674   /// both completed, the value of the resulting Future<bool> will be true. It
675   /// will be false otherwise (including when one or both Futures have an
676   /// exception)
677   Future<bool> willEqual(Future<T>&);
678
679   /// predicate behaves like std::function<bool(T const&)>
680   /// If the predicate does not obtain with the value, the result
681   /// is a folly::PredicateDoesNotObtain exception
682   template <class F>
683   Future<T> filter(F&& predicate);
684
685   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
686   /// the result of collect or collectAll
687   template <class I, class F>
688   Future<I> reduce(I&& initial, F&& func);
689
690   /// Create a Future chain from a sequence of callbacks. i.e.
691   ///
692   ///   f.then(a).then(b).then(c)
693   ///
694   /// where f is a Future<A> and the result of the chain is a Future<D>
695   /// becomes
696   ///
697   ///   f.thenMulti(a, b, c);
698   template <class Callback, class... Callbacks>
699   auto thenMulti(Callback&& fn, Callbacks&&... fns) {
700     // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
701     return then(std::forward<Callback>(fn))
702         .thenMulti(std::forward<Callbacks>(fns)...);
703   }
704
705   template <class Callback>
706   auto thenMulti(Callback&& fn) {
707     // thenMulti with one callback is just a then
708     return then(std::forward<Callback>(fn));
709   }
710
711   /// Create a Future chain from a sequence of callbacks. i.e.
712   ///
713   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
714   ///
715   /// where f is a Future<A> and the result of the chain is a Future<D>
716   /// becomes
717   ///
718   ///   f.thenMultiWithExecutor(executor, a, b, c);
719   template <class Callback, class... Callbacks>
720   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
721     // thenMultiExecutor with two callbacks is
722     // via(x).then(a).thenMulti(b, ...).via(oldX)
723     auto oldX = this->getExecutor();
724     this->setExecutor(x);
725     return then(std::forward<Callback>(fn))
726         .thenMulti(std::forward<Callbacks>(fns)...)
727         .via(oldX);
728   }
729
730   template <class Callback>
731   auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
732     // thenMulti with one callback is just a then with an executor
733     return then(x, std::forward<Callback>(fn));
734   }
735
736   // Convert this Future to a SemiFuture to safely export from a library
737   // without exposing a continuation interface
738   SemiFuture<T> semi() {
739     return SemiFuture<T>{std::move(*this)};
740   }
741
742  protected:
743   friend class Promise<T>;
744   template <class>
745   friend class futures::detail::FutureBase;
746   template <class>
747   friend class Future;
748   template <class>
749   friend class SemiFuture;
750
751   using Base::setExecutor;
752   using Base::throwIfInvalid;
753   using typename Base::corePtr;
754
755   explicit Future(corePtr obj) : Base(obj) {}
756
757   explicit Future(futures::detail::EmptyConstruct) noexcept
758       : Base(futures::detail::EmptyConstruct{}) {}
759
760   template <class T2>
761   friend Future<T2> makeFuture(Try<T2>&&);
762
763   /// Repeat the given future (i.e., the computation it contains)
764   /// n times.
765   ///
766   /// thunk behaves like std::function<Future<T2>(void)>
767   template <class F>
768   friend Future<Unit> times(int n, F&& thunk);
769
770   /// Carry out the computation contained in the given future if
771   /// the predicate holds.
772   ///
773   /// thunk behaves like std::function<Future<T2>(void)>
774   template <class F>
775   friend Future<Unit> when(bool p, F&& thunk);
776
777   /// Carry out the computation contained in the given future if
778   /// while the predicate continues to hold.
779   ///
780   /// thunk behaves like std::function<Future<T2>(void)>
781   ///
782   /// predicate behaves like std::function<bool(void)>
783   template <class P, class F>
784   friend Future<Unit> whileDo(P&& predicate, F&& thunk);
785 };
786
787 } // namespace folly
788
789 #include <folly/futures/Future-inl.h>