Skip to content

Commit 5accefb

Browse files
authored
Merge pull request #98 from Snapchat/bkotsopoulossc-patch-1
[Future] Suppose resolve/reject convenience methods
2 parents a6405c3 + f6011bb commit 5accefb

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

support-lib/cpp/Future.hpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,49 @@ class PromiseBase {
108108
public:
109109
Future<T> getFuture();
110110

111+
// Use to immediately resolve a promise and return the resulting future.
112+
// Useful for returning from trivial cases in functions that return djinni::Future<>
113+
// Examples:
114+
// return Promise<int>::resolve(4);
115+
// return Promise<std::string>::resolve(std::move(someStr));
116+
static Future<T> resolve(const typename ValueHolder<T>::type& val) {
117+
PromiseBase<T> promise;
118+
promise.setValue(val);
119+
return promise.getFuture();
120+
}
121+
static Future<T> resolve(typename ValueHolder<T>::type&& val) {
122+
PromiseBase<T> promise;
123+
promise.setValue(std::move(val));
124+
return promise.getFuture();
125+
}
126+
127+
// Use to immediately reject a promise and return the resulting future.
128+
// Useful for returning from synchronous error handling in functions that return djinni::Future<>
129+
// Examples:
130+
// return Promise<int>::reject(std::runtime_error("something bad"));
131+
//
132+
// try {
133+
// throwingFunc();
134+
// } catch (const std::exception& e) {
135+
// return Promise<std::string>::reject(e);
136+
// }
137+
//
138+
// try {
139+
// throwingFunc();
140+
// } catch (...) {
141+
// return Promise<std::string>::reject(std::current_exception());
142+
// }
143+
static Future<T> reject(const std::exception& e) {
144+
PromiseBase<T> promise;
145+
promise.setException(e);
146+
return promise.getFuture();
147+
}
148+
static Future<T> reject(std::exception_ptr ex) {
149+
PromiseBase<T> promise;
150+
promise.setException(ex);
151+
return promise.getFuture();
152+
}
153+
111154
protected:
112155
// `setValue()` or `setException()` can only be called once. After which the
113156
// shared state is set to null and further calls to `setValue()` or

0 commit comments

Comments
 (0)