Add getSemiFuture to folly::Promise
[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   /** A reference to the Try of the value */
110   Try<T>& getTry();
111
112   /// If the promise has been fulfilled, return an Optional with the Try<T>.
113   /// Otherwise return an empty Optional.
114   /// Note that this moves the Try<T> out.
115   Optional<Try<T>> poll();
116
117   /// This is not the method you're looking for.
118   ///
119   /// This needs to be public because it's used by make* and when*, and it's
120   /// not worth listing all those and their fancy template signatures as
121   /// friends. But it's not for public consumption.
122   template <class F>
123   void setCallback_(F&& func);
124
125   bool isActive() {
126     return core_->isActive();
127   }
128
129   template <class E>
130   void raise(E&& exception) {
131     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
132         std::forward<E>(exception)));
133   }
134
135   /// Raise an interrupt. If the promise holder has an interrupt
136   /// handler it will be called and potentially stop asynchronous work from
137   /// being done. This is advisory only - a promise holder may not set an
138   /// interrupt handler, or may do anything including ignore. But, if you know
139   /// your future supports this the most likely result is stopping or
140   /// preventing the asynchronous operation (if in time), and the promise
141   /// holder setting an exception on the future. (That may happen
142   /// asynchronously, of course.)
143   void raise(exception_wrapper interrupt);
144
145   void cancel() {
146     raise(FutureCancellation());
147   }
148
149  protected:
150   friend class Promise<T>;
151   template <class>
152   friend class SemiFuture;
153   template <class>
154   friend class Future;
155
156   using corePtr = futures::detail::Core<T>*;
157
158   // shared core state object
159   corePtr core_;
160
161   explicit FutureBase(corePtr obj) : core_(obj) {}
162
163   explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
164
165   void detach();
166
167   void throwIfInvalid() const;
168
169   template <class FutureType>
170   void assign(FutureType&) noexcept;
171
172   Executor* getExecutor() {
173     return core_->getExecutor();
174   }
175
176   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
177     core_->setExecutor(x, priority);
178   }
179
180   // Variant: returns a value
181   // e.g. f.then([](Try<T> t){ return t.value(); });
182   template <typename F, typename R, bool isTry, typename... Args>
183   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
184   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
185
186   // Variant: returns a Future
187   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
188   template <typename F, typename R, bool isTry, typename... Args>
189   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
190   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
191 };
192 } // namespace detail
193 } // namespace futures
194
195 template <class T>
196 class SemiFuture : private futures::detail::FutureBase<T> {
197  private:
198   using Base = futures::detail::FutureBase<T>;
199   using DeferredExecutor = futures::detail::DeferredExecutor;
200
201  public:
202   static SemiFuture<T> makeEmpty(); // equivalent to moved-from
203
204   // Export public interface of FutureBase
205   // FutureBase is inherited privately to avoid subclasses being cast to
206   // a FutureBase pointer
207   using typename Base::value_type;
208
209   /// Construct a Future from a value (perfect forwarding)
210   template <
211       class T2 = T,
212       typename = typename std::enable_if<
213           !isFuture<typename std::decay<T2>::type>::value &&
214           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
215   /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
216
217   template <class T2 = T>
218   /* implicit */ SemiFuture(
219       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
220       : Base(p) {}
221
222   template <
223       class... Args,
224       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
225           type = 0>
226   explicit SemiFuture(in_place_t, Args&&... args)
227       : Base(in_place, std::forward<Args>(args)...) {}
228
229   SemiFuture(SemiFuture<T> const&) = delete;
230   // movable
231   SemiFuture(SemiFuture<T>&&) noexcept;
232   // safe move-constructabilty from Future
233   /* implicit */ SemiFuture(Future<T>&&) noexcept;
234
235   using Base::cancel;
236   using Base::getTry;
237   using Base::hasException;
238   using Base::hasValue;
239   using Base::isActive;
240   using Base::isReady;
241   using Base::poll;
242   using Base::raise;
243   using Base::setCallback_;
244   using Base::value;
245
246   SemiFuture& operator=(SemiFuture const&) = delete;
247   SemiFuture& operator=(SemiFuture&&) noexcept;
248   SemiFuture& operator=(Future<T>&&) noexcept;
249
250   /// Block until the future is fulfilled. Returns the value (moved out), or
251   /// throws the exception. The future must not already have a callback.
252   T get() &&;
253
254   /// Block until the future is fulfilled, or until timed out. Returns the
255   /// value (moved out), or throws the exception (which might be a TimedOut
256   /// exception).
257   T get(Duration dur) &&;
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::getTry;
396   using Base::hasException;
397   using Base::hasValue;
398   using Base::isActive;
399   using Base::isReady;
400   using Base::poll;
401   using Base::raise;
402   using Base::setCallback_;
403   using Base::value;
404
405   static Future<T> makeEmpty(); // equivalent to moved-from
406
407   // not copyable
408   Future& operator=(Future const&) = delete;
409
410   // movable
411   Future& operator=(Future&&) noexcept;
412
413   /// Call e->drive() repeatedly until the future is fulfilled. Examples
414   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
415   /// reference to the Try of the value.
416   Try<T>& getTryVia(DrivableExecutor* e);
417
418   /// Call e->drive() repeatedly until the future is fulfilled. Examples
419   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
420   /// value (moved out), or throws the exception.
421   T getVia(DrivableExecutor* e);
422
423   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
424   /// Future<T> instance.
425   template <class F = T>
426   typename std::
427       enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
428       unwrap();
429
430   /// Returns an inactive Future which will call back on the other side of
431   /// executor (when it is activated).
432   ///
433   /// NB remember that Futures activate when they destruct. This is good,
434   /// it means that this will work:
435   ///
436   ///   f.via(e).then(a).then(b);
437   ///
438   /// a and b will execute in the same context (the far side of e), because
439   /// the Future (temporary variable) created by via(e) does not call back
440   /// until it destructs, which is after then(a) and then(b) have been wired
441   /// up.
442   ///
443   /// But this is still racy:
444   ///
445   ///   f = f.via(e).then(a);
446   ///   f.then(b);
447   // The ref-qualifier allows for `this` to be moved out so we
448   // don't get access-after-free situations in chaining.
449   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
450   inline Future<T> via(
451       Executor* executor,
452       int8_t priority = Executor::MID_PRI) &&;
453
454   /// This variant creates a new future, where the ref-qualifier && version
455   /// moves `this` out. This one is less efficient but avoids confusing users
456   /// when "return f.via(x);" fails.
457   inline Future<T> via(
458       Executor* executor,
459       int8_t priority = Executor::MID_PRI) &;
460
461   /** When this Future has completed, execute func which is a function that
462     takes one of:
463       (const) Try<T>&&
464       (const) Try<T>&
465       (const) Try<T>
466       (const) T&&
467       (const) T&
468       (const) T
469       (void)
470
471     Func shall return either another Future or a value.
472
473     A Future for the return type of func is returned.
474
475     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
476
477     The Future given to the functor is ready, and the functor may call
478     value(), which may rethrow if this has captured an exception. If func
479     throws, the exception will be captured in the Future that is returned.
480     */
481   template <typename F, typename R = futures::detail::callableResult<T, F>>
482   typename R::Return then(F&& func) {
483     return this->template thenImplementation<F, R>(
484         std::forward<F>(func), typename R::Arg());
485   }
486
487   /// Variant where func is an member function
488   ///
489   ///   struct Worker { R doWork(Try<T>); }
490   ///
491   ///   Worker *w;
492   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
493   ///
494   /// This is just sugar for
495   ///
496   ///   f1.then(std::bind(&Worker::doWork, w));
497   template <typename R, typename Caller, typename... Args>
498   Future<typename isFuture<R>::Inner> then(
499       R (Caller::*func)(Args...),
500       Caller* instance);
501
502   /// Execute the callback via the given Executor. The executor doesn't stick.
503   ///
504   /// Contrast
505   ///
506   ///   f.via(x).then(b).then(c)
507   ///
508   /// with
509   ///
510   ///   f.then(x, b).then(c)
511   ///
512   /// In the former both b and c execute via x. In the latter, only b executes
513   /// via x, and c executes via the same executor (if any) that f had.
514   template <class Executor, class Arg, class... Args>
515   auto then(Executor* x, Arg&& arg, Args&&... args) {
516     auto oldX = this->getExecutor();
517     this->setExecutor(x);
518     return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
519         .via(oldX);
520   }
521
522   /// Convenience method for ignoring the value and creating a Future<Unit>.
523   /// Exceptions still propagate.
524   /// This function is identical to .unit().
525   Future<Unit> then();
526
527   /// Convenience method for ignoring the value and creating a Future<Unit>.
528   /// Exceptions still propagate.
529   /// This function is identical to parameterless .then().
530   Future<Unit> unit() {
531     return then();
532   }
533
534   /// Set an error callback for this Future. The callback should take a single
535   /// argument of the type that you want to catch, and should return a value of
536   /// the same type as this Future, or a Future of that type (see overload
537   /// below). For instance,
538   ///
539   /// makeFuture()
540   ///   .then([] {
541   ///     throw std::runtime_error("oh no!");
542   ///     return 42;
543   ///   })
544   ///   .onError([] (std::runtime_error& e) {
545   ///     LOG(INFO) << "std::runtime_error: " << e.what();
546   ///     return -1; // or makeFuture<int>(-1)
547   ///   });
548   template <class F>
549   typename std::enable_if<
550       !futures::detail::callableWith<F, exception_wrapper>::value &&
551           !futures::detail::callableWith<F, exception_wrapper&>::value &&
552           !futures::detail::Extract<F>::ReturnsFuture::value,
553       Future<T>>::type
554   onError(F&& func);
555
556   /// Overload of onError where the error callback returns a Future<T>
557   template <class F>
558   typename std::enable_if<
559       !futures::detail::callableWith<F, exception_wrapper>::value &&
560           !futures::detail::callableWith<F, exception_wrapper&>::value &&
561           futures::detail::Extract<F>::ReturnsFuture::value,
562       Future<T>>::type
563   onError(F&& func);
564
565   /// Overload of onError that takes exception_wrapper and returns Future<T>
566   template <class F>
567   typename std::enable_if<
568       futures::detail::callableWith<F, exception_wrapper>::value &&
569           futures::detail::Extract<F>::ReturnsFuture::value,
570       Future<T>>::type
571   onError(F&& func);
572
573   /// Overload of onError that takes exception_wrapper and returns T
574   template <class F>
575   typename std::enable_if<
576       futures::detail::callableWith<F, exception_wrapper>::value &&
577           !futures::detail::Extract<F>::ReturnsFuture::value,
578       Future<T>>::type
579   onError(F&& func);
580
581   /// func is like std::function<void()> and is executed unconditionally, and
582   /// the value/exception is passed through to the resulting Future.
583   /// func shouldn't throw, but if it does it will be captured and propagated,
584   /// and discard any value/exception that this Future has obtained.
585   template <class F>
586   Future<T> ensure(F&& func);
587
588   /// Like onError, but for timeouts. example:
589   ///
590   ///   Future<int> f = makeFuture<int>(42)
591   ///     .delayed(long_time)
592   ///     .onTimeout(short_time,
593   ///       []() -> int{ return -1; });
594   ///
595   /// or perhaps
596   ///
597   ///   Future<int> f = makeFuture<int>(42)
598   ///     .delayed(long_time)
599   ///     .onTimeout(short_time,
600   ///       []() { return makeFuture<int>(some_exception); });
601   template <class F>
602   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
603
604   /// A Future's callback is executed when all three of these conditions have
605   /// become true: it has a value (set by the Promise), it has a callback (set
606   /// by then), and it is active (active by default).
607   ///
608   /// Inactive Futures will activate upon destruction.
609   FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
610     this->core_->activate();
611     return *this;
612   }
613   FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
614     this->core_->deactivate();
615     return *this;
616   }
617   FOLLY_DEPRECATED("do not use") Future<T> activate() && {
618     this->core_->activate();
619     return std::move(*this);
620   }
621   FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
622     this->core_->deactivate();
623     return std::move(*this);
624   }
625
626   /// Throw TimedOut if this Future does not complete within the given
627   /// duration from now. The optional Timeekeeper is as with futures::sleep().
628   Future<T> within(Duration, Timekeeper* = nullptr);
629
630   /// Throw the given exception if this Future does not complete within the
631   /// given duration from now. The optional Timeekeeper is as with
632   /// futures::sleep().
633   template <class E>
634   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
635
636   /// Delay the completion of this Future for at least this duration from
637   /// now. The optional Timekeeper is as with futures::sleep().
638   Future<T> delayed(Duration, Timekeeper* = nullptr);
639
640   /// Block until the future is fulfilled. Returns the value (moved out), or
641   /// throws the exception. The future must not already have a callback.
642   T get();
643
644   /// Block until the future is fulfilled, or until timed out. Returns the
645   /// value (moved out), or throws the exception (which might be a TimedOut
646   /// exception).
647   T get(Duration dur);
648
649   /// Block until this Future is complete. Returns a reference to this Future.
650   Future<T>& wait() &;
651
652   /// Overload of wait() for rvalue Futures
653   Future<T>&& wait() &&;
654
655   /// Block until this Future is complete or until the given Duration passes.
656   /// Returns a reference to this Future
657   Future<T>& wait(Duration) &;
658
659   /// Overload of wait(Duration) for rvalue Futures
660   Future<T>&& wait(Duration) &&;
661
662   /// Call e->drive() repeatedly until the future is fulfilled. Examples
663   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
664   /// reference to this Future so that you can chain calls if desired.
665   /// value (moved out), or throws the exception.
666   Future<T>& waitVia(DrivableExecutor* e) &;
667
668   /// Overload of waitVia() for rvalue Futures
669   Future<T>&& waitVia(DrivableExecutor* e) &&;
670
671   /// If the value in this Future is equal to the given Future, when they have
672   /// both completed, the value of the resulting Future<bool> will be true. It
673   /// will be false otherwise (including when one or both Futures have an
674   /// exception)
675   Future<bool> willEqual(Future<T>&);
676
677   /// predicate behaves like std::function<bool(T const&)>
678   /// If the predicate does not obtain with the value, the result
679   /// is a folly::PredicateDoesNotObtain exception
680   template <class F>
681   Future<T> filter(F&& predicate);
682
683   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
684   /// the result of collect or collectAll
685   template <class I, class F>
686   Future<I> reduce(I&& initial, F&& func);
687
688   /// Create a Future chain from a sequence of callbacks. i.e.
689   ///
690   ///   f.then(a).then(b).then(c)
691   ///
692   /// where f is a Future<A> and the result of the chain is a Future<D>
693   /// becomes
694   ///
695   ///   f.thenMulti(a, b, c);
696   template <class Callback, class... Callbacks>
697   auto thenMulti(Callback&& fn, Callbacks&&... fns) {
698     // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
699     return then(std::forward<Callback>(fn))
700         .thenMulti(std::forward<Callbacks>(fns)...);
701   }
702
703   template <class Callback>
704   auto thenMulti(Callback&& fn) {
705     // thenMulti with one callback is just a then
706     return then(std::forward<Callback>(fn));
707   }
708
709   /// Create a Future chain from a sequence of callbacks. i.e.
710   ///
711   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
712   ///
713   /// where f is a Future<A> and the result of the chain is a Future<D>
714   /// becomes
715   ///
716   ///   f.thenMultiWithExecutor(executor, a, b, c);
717   template <class Callback, class... Callbacks>
718   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
719     // thenMultiExecutor with two callbacks is
720     // via(x).then(a).thenMulti(b, ...).via(oldX)
721     auto oldX = this->getExecutor();
722     this->setExecutor(x);
723     return then(std::forward<Callback>(fn))
724         .thenMulti(std::forward<Callbacks>(fns)...)
725         .via(oldX);
726   }
727
728   template <class Callback>
729   auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
730     // thenMulti with one callback is just a then with an executor
731     return then(x, std::forward<Callback>(fn));
732   }
733
734   // Convert this Future to a SemiFuture to safely export from a library
735   // without exposing a continuation interface
736   SemiFuture<T> semi() {
737     return SemiFuture<T>{std::move(*this)};
738   }
739
740  protected:
741   friend class Promise<T>;
742   template <class>
743   friend class futures::detail::FutureBase;
744   template <class>
745   friend class Future;
746   template <class>
747   friend class SemiFuture;
748
749   using Base::setExecutor;
750   using Base::throwIfInvalid;
751   using typename Base::corePtr;
752
753   explicit Future(corePtr obj) : Base(obj) {}
754
755   explicit Future(futures::detail::EmptyConstruct) noexcept
756       : Base(futures::detail::EmptyConstruct{}) {}
757
758   template <class T2>
759   friend Future<T2> makeFuture(Try<T2>&&);
760
761   /// Repeat the given future (i.e., the computation it contains)
762   /// n times.
763   ///
764   /// thunk behaves like std::function<Future<T2>(void)>
765   template <class F>
766   friend Future<Unit> times(int n, F&& thunk);
767
768   /// Carry out the computation contained in the given future if
769   /// the predicate holds.
770   ///
771   /// thunk behaves like std::function<Future<T2>(void)>
772   template <class F>
773   friend Future<Unit> when(bool p, F&& thunk);
774
775   /// Carry out the computation contained in the given future if
776   /// while the predicate continues to hold.
777   ///
778   /// thunk behaves like std::function<Future<T2>(void)>
779   ///
780   /// predicate behaves like std::function<bool(void)>
781   template <class P, class F>
782   friend Future<Unit> whileDo(P&& predicate, F&& thunk);
783 };
784
785 } // namespace folly
786
787 #include <folly/futures/Future-inl.h>