-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathKLib.Promise.pas
433 lines (364 loc) · 12.1 KB
/
KLib.Promise.pas
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
{
KLib Version = 3.0
The Clear BSD License
Copyright (c) 2020 by Karol De Nery Ortiz LLave. All rights reserved.
zitrokarol@gmail.com
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the disclaimer
below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
unit KLib.Promise;
interface
uses
KLib.Types, Klib.Constants, KLib.ListOfThreads, KLib.MyEvent,
System.Classes;
type
TPromise = class
private
_executorFunction: TExecutorFunction;
_alreadyExecuted: boolean;
_autoClean: boolean;
_autoCleanSetted: boolean;
_promiseFinished_event: TMyEvent;
_executor_thread: TThread;
_then_threadList: TListOfThreads;
_catch_threadList: TListOfThreads;
_default_reject_callback: TCallBack;
procedure execute;
procedure executeInAnonymousThread;
procedure resolve(msg: string);
procedure reject(msg: string);
public
status: TAsyncMethodStatus;
resultOfPromise: string;
constructor Create(_method: KLib.Types.TMethod;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN); reintroduce; overload;
constructor Create(_procedure: KLib.Types.TProcedure;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN); reintroduce; overload;
constructor Create(_anonymousMethod: KLib.Types.TAnonymousMethod;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN); reintroduce; overload;
//autoClean is like a FreeOnTerminate on TThread
constructor Create(executorFunction: TExecutorFunction; callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN); reintroduce; overload;
constructor Create(executorFunction: TExecutorFunction; _then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN); reintroduce; overload;
function setCallbacks(callbacks: TCallBacks): TPromise; overload;
function _then(onFulfilled: TCallBack; onRejected: TCallBack): TPromise; overload;
function _then(onFulfilled: TCallBack): TPromise; overload;
function _catch(onRejected: TCallback): TPromise;
procedure _finally; overload;
procedure _finally(onFinally: KLib.Types.TAnonymousMethod); overload;
destructor Destroy; override;
end;
TArrayOfPromises = array of TPromise; //not move in KLib.Types (circular reference)
function promisify(_method: KLib.Types.TMethod;
callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
function promisify(_method: KLib.Types.TMethod;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
function promisify(_procedure: KLib.Types.TProcedure;
callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
function promisify(_procedure: KLib.Types.TProcedure;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
function promisify(_anonymousMethod: KLib.Types.TAnonymousMethod;
callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
function promisify(_anonymousMethod: KLib.Types.TAnonymousMethod;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
implementation
uses
Winapi.ActiveX,
System.SysUtils;
type
EExitPromise = class(EAbort);
function promisify(_method: KLib.Types.TMethod;
callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN): TPromise;
begin
Result := promisify(_method, callBacks.resolve, callBacks.reject, autoClean);
end;
function promisify(_method: KLib.Types.TMethod; _then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
begin
Result := TPromise.Create(_method, _then, _catch, autoClean);
end;
function promisify(_procedure: KLib.Types.TProcedure;
callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN): TPromise;
begin
Result := promisify(_procedure, callBacks.resolve, callBacks.reject, autoClean);
end;
function promisify(_procedure: KLib.Types.TProcedure; _then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN): TPromise; overload;
begin
Result := TPromise.Create(_procedure, _then, _catch, autoClean);
end;
function promisify(_anonymousMethod: KLib.Types.TAnonymousMethod;
callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN): TPromise;
begin
Result := promisify(_anonymousMethod, callBacks.resolve, callBacks.reject, autoClean);
end;
function promisify(_anonymousMethod: KLib.Types.TAnonymousMethod; _then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN): TPromise;
begin
Result := TPromise.Create(_anonymousMethod, _then, _catch, autoClean);
end;
constructor TPromise.Create(_method: KLib.Types.TMethod;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN);
begin
Create(
procedure
begin
_method;
end,
_then, _catch, autoClean);
end;
constructor TPromise.Create(_procedure: KLib.Types.TProcedure;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN);
begin
Create(
procedure
begin
_procedure;
end,
_then, _catch, autoClean);
end;
constructor TPromise.Create(_anonymousMethod: KLib.Types.TAnonymousMethod;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN);
var
_thenTemp: TCallBack;
_catchTemp: TCallBack;
begin
if Assigned(_then) then
begin
_thenTemp := _then;
end
else
begin
_thenTemp := procedure(value: String)
begin
end;
end;
if Assigned(_catch) then
begin
_catchTemp := _catch;
end
else
begin
_catchTemp := procedure(value: String)
begin
raise Exception.Create(value);
end;
end;
Create(
procedure(resolve: TCallBack; reject: TCallback)
begin
_anonymousMethod;
resolve('Promise resolved');
end,
_thenTemp,
_catchTemp,
autoClean);
end;
constructor TPromise.Create(executorFunction: TExecutorFunction; callBacks: TCallbacks; autoClean: boolean = NOT_AUTO_CLEAN);
begin
Create(executorFunction, TCallBack(callBacks.resolve), TCallback(callBacks.reject), autoClean);
end;
constructor TPromise.Create(executorFunction: TExecutorFunction;
_then: TCallBack = nil; _catch: TCallback = nil; autoClean: boolean = NOT_AUTO_CLEAN);
begin
Self._then_threadList := TListOfThreads.Create;
Self._catch_threadList := TListOfThreads.Create;
Self._promiseFinished_event := TMyEvent.Create;
Self.status := TAsyncMethodStatus.created;
Self._executorFunction := executorFunction;
Self._autoClean := autoClean;
Self._autoCleanSetted := false;
execute;
if Assigned(_then) then
begin
Self._then(_then);
end;
if Assigned(_catch) then
begin
Self._catch(_catch);
end;
end;
procedure TPromise.execute;
begin
if (not _alreadyExecuted) then
begin
_alreadyExecuted := true;
Self.status := TAsyncMethodStatus.pending;
executeInAnonymousThread;
end;
end;
procedure TPromise.executeInAnonymousThread;
begin
_executor_thread := TThread.CreateAnonymousThread(
procedure
begin
CoInitialize(nil);
try
try
_executorFunction(resolve, reject);
except
on e: Exception do
begin
if (e.ClassType <> EExitPromise) then
begin
reject(e.Message);
end;
end;
end;
finally
CoUninitialize;
end;
end);
_executor_thread.FreeOnTerminate := False;
_executor_thread.Start;
if _autoClean then
begin
_finally;
end;
end;
function TPromise.setCallbacks(callbacks: TCallBacks): TPromise;
begin
_then(callbacks.resolve, callbacks.reject);
Result := Self;
end;
function TPromise._then(onFulfilled: TCallBack; onRejected: TCallBack): TPromise;
begin
_then(onFulfilled);
_catch(onRejected);
Result := Self;
end;
function TPromise._then(onFulfilled: TCallBack): TPromise;
var
_then_thread: TThread;
begin
_then_thread := TThread.CreateAnonymousThread(
procedure
begin
CoInitialize(nil);
try
_promiseFinished_event.waitForInfinite;
if status = TAsyncMethodStatus.fulfilled then
begin
try
onFulfilled(resultOfPromise);
except
on E: Exception do
begin
if (e.ClassType <> EExitPromise) then
begin
_default_reject_callback(e.Message);
end;
end;
end;
end;
finally
CoUninitialize;
end;
end);
_then_thread.FreeOnTerminate := False;
_then_thread.Start;
_then_threadList.Add(_then_thread);
Result := Self;
end;
function TPromise._catch(onRejected: TCallback): TPromise;
var
_catch_thread: TThread;
begin
if not Assigned(_default_reject_callback) then
begin
_default_reject_callback := onRejected;
end;
_catch_thread := TThread.CreateAnonymousThread(
procedure
begin
CoInitialize(nil);
try
_promiseFinished_event.waitForInfinite;
if status = TAsyncMethodStatus.rejected then
begin
onRejected(resultOfPromise);
end;
finally
CoUninitialize;
end;
end);
_catch_thread.FreeOnTerminate := False;
_catch_thread.Start;
_catch_threadList.Add(_catch_thread);
Result := Self;
end;
procedure TPromise._finally;
begin
_finally(
procedure
begin
end);
end;
procedure TPromise._finally(onFinally: KLib.Types.TAnonymousMethod);
begin
if _autoCleanSetted then
begin
raise Exception.Create('TPromise.autoClean property already setted');
end;
TThread.CreateAnonymousThread(
procedure
begin
CoInitialize(nil);
try
_promiseFinished_event.waitForInfinite;
_then_threadList.WaitFor;
_catch_threadList.WaitFor;
onFinally;
finally
CoUninitialize;
Self.Destroy;
end;
end).Start;
Self._autoCleanSetted := true;
end;
procedure TPromise.resolve(msg: string);
begin
if (status = TAsyncMethodStatus.pending) then
begin
resultOfPromise := msg;
status := TAsyncMethodStatus.fulfilled;
_promiseFinished_event.enable;
raise EExitPromise.Create('force exit in resolve procedure');
end;
end;
procedure TPromise.reject(msg: string);
begin
if (status = TAsyncMethodStatus.pending) then
begin
resultOfPromise := msg;
status := TAsyncMethodStatus.rejected;
_promiseFinished_event.enable;
raise EExitPromise.Create('force exit in reject procedure');
end;
end;
destructor TPromise.Destroy;
begin
FreeAndNil(_executor_thread);
FreeAndNil(_then_threadList);
FreeAndNil(_catch_threadList);
_promiseFinished_event.Free;
inherited;
end;
end.