-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJSLikePromiseAny.hpp
298 lines (253 loc) · 11.1 KB
/
JSLikePromiseAny.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#pragma once
#pragma once
#include <iostream>
#include <coroutine>
#include <memory>
#include <functional>
#include <exception>
#include <vector>
#include "JSLikePromise.hpp"
#include "JSLikeBasePromise.hpp"
namespace JSLike {
using namespace std;
struct PromiseAnyState : public PromiseState<shared_ptr<BasePromiseState>> {
PromiseAnyState() = default;
private:
friend struct PromiseAny;
// Don't allow copies of any kind. Always use std::shared_ptr to instances of this type.
PromiseAnyState(const PromiseAnyState&) = delete;
PromiseAnyState(PromiseAnyState&& other) = delete;
PromiseAnyState& operator=(const PromiseAnyState&) = delete;
void init(shared_ptr<PromiseAnyState> &thisState, vector<BasePromise> const &monitoredPromises)
{
size_t vectorSize = monitoredPromises.size();
if (vectorSize == 0) {
resolve(Promise<>().state());
return;
}
for (size_t i = 0; i < vectorSize; i++) {
auto monitoredPromise = monitoredPromises[i];
auto monitoredPromiseState = monitoredPromise.m_state;
// May call BasePromiseState::Then() or PromiseAnyState::Then()
monitoredPromiseState->Then(
[thisState, monitoredPromiseState](shared_ptr<BasePromiseState> resultState) // Note that the Lambda keeps a shared_ptr to this PromiseAllState
{
// Call PromiseAnyState::resolve()
thisState->resolve(resultState);
},
[thisState](auto ex) // Note that the Lambda keeps a shared_ptr to this PromiseAllState
{
thisState->reject(ex);
});
// Optimization: If already resolved/rejected, then don't add any more "Then" or "Catch".
if (m_eptr || m_isResolved) return;
}
}
// Override BasePromiseState::Then()
void Then(BasePromise::ThenCallback thenCallback) override {
m_thenCallback = thenCallback;
if (m_isResolved) {
thenCallback(value()); // Difference vs. BasePromiseState
}
}
// Override PromiseState::resolve()
void resolve(shared_ptr<BasePromiseState> const &result) {
if (m_eptr || m_isResolved) return;
m_result = make_shared<shared_ptr<BasePromiseState>>(result);
BasePromiseState::resolve(result); // Difference vs. PromiseState
}
}; // PromiseAnyState
/**
* A PromiseAny is initialized/constructed with a vector of BasePromises (e.g. BasePromises,
* Promise<T>s, or other PromiseAnys), which it then monitors for resolution or rejection.
*
* After one of the BasePromises is resolved, the PromiseAny's "Then" lambda is called with a
* PromiseAny::ResultType (see typedef), which is a shared pointer to the
* BasePromiseState (of the BasePromises) that was resolved. The Lambda can retrieve the
* type and value of the (derived) BasePromiseState by calling BasePromiseState::isValueOfType<T>()
* and BasePromiseState::value<T>(). Example:
*
* void myFunction(BasePromise &p0, BasePromise &p1, BasePromise &p2, BasePromise &p3)
* {
* PromiseAny pa({ p0, p1, p2, p3 }); // One of these promises is resolved elsewhere.
* pa.Then([&](auto state) // The type of states is PromiseAny::ResultType.
* {
* if(state->isValueOfType<int>()) cout << state->value<int>();
* if(state->isValueOfType<string>()) cout << state->value<string>();
* if(state->isValueOfType<double>()) cout << state->value<double>();
* // In this example we suppose that, p0 is BasePromiseState, so it doesn't have a value.
* });
* }
*
* A PromiseAny is rejected if any of the BasePromises with which it is constructed/initialized
* is rejected. It's "Catch" Lambda is called with the same exception_ptr with which the
* BasePromise was rejected.
*
* Coroutines can return a PromiseAny, which is "wired up" to settle at the same time and with
* the same result as the PromiseAany resulting from co_return.
*/
struct PromiseAny : public BasePromise {
public:
typedef shared_ptr<BasePromiseState> ResultType;
PromiseAny() {
auto s = state();
auto ex = make_exception_ptr(logic_error("PromiseAny constructed with empty array"));
s->reject(ex);
};
/**
* Construct a PromiseAny with the vector of BasePromises that it will monitor for resolution/rejection.
* @param promises The vector of BasePromises.
*/
PromiseAny(vector<BasePromise> const &promises)
{
auto s = state();
s->init(s, promises);
}
PromiseAny(function<void(shared_ptr<BasePromiseState>)>) = delete;
shared_ptr<PromiseAnyState> state() {
if (!m_state) m_state = make_shared<PromiseAnyState>();
auto castState = dynamic_pointer_cast<PromiseAnyState>(m_state);
return castState;
}
PromiseAny Then(ThenCallback thenCallback) {
PromiseAny chainedPromise(false); // The new "chained" Promise that we'll return to the caller.
auto chainedPromiseState = chainedPromise.state();
// Create a "bridge" between the current Promise and the new "chained" Promise that we'll return.
// When this Promise gets settled, one of the following two Lambdas will settle the "chained" promise.
// Note that the Lambdas only operate on the PromiseState of each Promise. The Promises are just
// "handles" to the Promise states.
auto currentState = state();
currentState->BasePromiseState::Then(
// Then Lambda
[chainedPromiseState, thenCallback](shared_ptr<BasePromiseState> resolvedState)
{
thenCallback(resolvedState);
chainedPromiseState->resolve(resolvedState); // difference vs. Promise<T>::Then()
},
// Catch Lambda
[chainedPromiseState](exception_ptr ex)
{
chainedPromiseState->reject(ex);
}
);
return chainedPromise;
}
PromiseAny Catch(CatchCallback catchCallback) {
PromiseAny chainedPromise(false);
auto chainedPromiseState = chainedPromise.state();
auto currentState = state();
// Create a "bridge" between the current Promise and the new "chained" Promise that we'll return.
// When this Promise gets settled, one of the following two Lambdas will settle the "chained" promise.
// Note that the Lambdas only operate on the PromiseState of each Promise. The Promises are just
// "handles" to the Promise states.
currentState->BasePromiseState::Then(
// Then Lambda
[chainedPromiseState](shared_ptr<BasePromiseState> resolvedState)
{
chainedPromiseState->resolve(resolvedState); // difference vs. Promise<T>::Catch()
},
// Catch Lambda
[chainedPromiseState, catchCallback](auto ex)
{
catchCallback(ex);
chainedPromiseState->reject(ex);
});
return chainedPromise;
}
PromiseAny Then(ThenCallback thenCallback, CatchCallback catchCallback) {
PromiseAny chainedPromise(false); // The new "chained" Promise that we'll return to the caller.
auto chainedPromiseState = chainedPromise.state();
// Create a "bridge" between the current Promise and the new "chained" Promise that we'll return.
// When this Promise gets settled, one of the following two Lambdas will settle the "chained" promise.
// Note that the Lambdas only operate on the PromiseState of each Promise. The Promises are just
// "handles" to the Promise states.
auto currentState = state();
currentState->BasePromiseState::Then(
// Then Lambda
[chainedPromiseState, thenCallback](shared_ptr<BasePromiseState> resolvedState)
{
thenCallback(resolvedState);
chainedPromiseState->resolve(resolvedState); // difference vs. Promise<T>::ThenCatch()
},
// Catch Lambda
[chainedPromiseState, catchCallback](auto ex)
{
catchCallback(ex);
chainedPromiseState->reject(ex);
});
return chainedPromise;
}
/**
* A promise_type is created each time a coroutine that returns PromiseAny is called.
* The promise_type immediately creates PromiseAny, which is returned to the caller.
*/
struct promise_type : promise_type_base {
/**
* Called when invoking a coroutine that returns a PromiseAny. This method creates
* a PromiseAny to return to the caller and saves a shared_ptr to its PromiseAny in
* this promise_type.
*
* Later, return_value() "wires up" the saved PromiseAnyState so that it settles
* when the PromiseAny evaluated by co_return settles.
*
* @return A pending PromiseAny that is not yet "wired up" to the PromiseAny evaluated
* by co_retrun.
*/
PromiseAny get_return_object() {
PromiseAny p(false);
m_state = p.state();
return p;
}
void return_value(PromiseAny coreturnedPromiseAny) {
auto savedPromiseAnyState = dynamic_pointer_cast<PromiseAnyState>(m_state);
auto coreturnedPromiseAnyState = coreturnedPromiseAny.state();
// Use a "Then" Lambda to get notified if coreturnedPromiseAll gets resolved.
coreturnedPromiseAnyState->BasePromiseState::Then(
[savedPromiseAnyState, coreturnedPromiseAnyState](shared_ptr<BasePromiseState> resultState)
{
// coreturnedPromiseAny got resolved, so resolve savedPromiseAnyState
savedPromiseAnyState->resolve(coreturnedPromiseAnyState->value());
},
// Use a "Catch" Lambda to get notified if savedPromiseAnyState gets rejected.
[savedPromiseAnyState](auto ex)
{
// coreturnedPromiseAny got rejected, so reject savedPromiseAnyState
savedPromiseAnyState->reject(ex);
});
}
};
struct awaiter_type : awaiter_type_base {
awaiter_type() = delete;
awaiter_type(const awaiter_type&) = delete;
awaiter_type(awaiter_type&& other) = default;
awaiter_type& operator=(const awaiter_type&) = delete;
awaiter_type(shared_ptr<BasePromiseState> state) : awaiter_type_base(state) {}
/**
* Called right before the call to co_await completes in order to return the result
* to the coroutine.
*
* @return The value with which resolve() was called.
*/
shared_ptr<BasePromiseState> await_resume() const {
m_state->rethrowIfRejected();
shared_ptr<PromiseAnyState> castState = dynamic_pointer_cast<PromiseAnyState>(m_state);
return castState->value();
}
};
/**
* Called by coroutines when they co_await on a PromiseAny.
* @return A PromiseAny::awaiter_type that suspends/resumes the coroutine as needed, and that returns to
* the coroutine the PromiseAny::ReturnType or rethrows an exception (e.g. for the coroutine to catch).
*/
awaiter_type operator co_await() {
awaiter_type a(state());
return a;
}
private:
PromiseAny(bool isResolved) {
auto s = state();
if (isResolved)
s->init(s, vector<BasePromise>{});
}
}; // PromiseAny
}; // namespace JSLike