2 * Copyright 2014-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.
22 #include <folly/executors/InlineExecutor.h>
23 #include <folly/futures/FutureException.h>
24 #include <folly/futures/detail/Core.h>
29 Promise<T> Promise<T>::makeEmpty() noexcept {
30 return Promise<T>(futures::detail::EmptyConstruct{});
35 : retrieved_(false), core_(new futures::detail::Core<T>()) {}
38 Promise<T>::Promise(Promise<T>&& other) noexcept
39 : retrieved_(other.retrieved_), core_(other.core_) {
40 other.core_ = nullptr;
41 other.retrieved_ = false;
45 Promise<T>& Promise<T>::operator=(Promise<T>&& other) noexcept {
46 std::swap(core_, other.core_);
47 std::swap(retrieved_, other.retrieved_);
52 void Promise<T>::throwIfFulfilled() {
57 throwPromiseAlreadySatisfied();
62 void Promise<T>::throwIfRetrieved() {
64 throwFutureAlreadyRetrieved();
69 Promise<T>::Promise(futures::detail::EmptyConstruct) noexcept
70 : retrieved_(false), core_(nullptr) {}
73 Promise<T>::~Promise() {
78 void Promise<T>::detach() {
81 core_->detachFuture();
83 core_->detachPromise();
89 SemiFuture<T> Promise<T>::getSemiFuture() {
92 return SemiFuture<T>(core_);
96 Future<T> Promise<T>::getFuture() {
97 // An InlineExecutor approximates the old behaviour of continuations
98 // running inine on setting the value of the promise.
99 return getSemiFuture().via(&InlineExecutor::instance());
104 typename std::enable_if<std::is_base_of<std::exception, E>::value>::type
105 Promise<T>::setException(E const& e) {
106 setException(make_exception_wrapper<E>(e));
110 void Promise<T>::setException(std::exception_ptr const& ep) {
111 setException(exception_wrapper::from_exception_ptr(ep));
115 void Promise<T>::setException(exception_wrapper ew) {
117 core_->setResult(Try<T>(std::move(ew)));
121 void Promise<T>::setInterruptHandler(
122 std::function<void(exception_wrapper const&)> fn) {
123 core_->setInterruptHandler(std::move(fn));
127 void Promise<T>::setTry(Try<T>&& t) {
129 core_->setResult(std::move(t));
134 void Promise<T>::setValue(M&& v) {
135 static_assert(!std::is_same<T, void>::value,
136 "Use setValue() instead");
138 setTry(Try<T>(std::forward<M>(v)));
143 void Promise<T>::setWith(F&& func) {
145 setTry(makeTryWith(std::forward<F>(func)));
149 bool Promise<T>::isFulfilled() const noexcept {
151 return core_->hasResult();