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