-
Notifications
You must be signed in to change notification settings - Fork 4
/
promises.bs
514 lines (454 loc) · 21.2 KB
/
promises.bs
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
' @rokucommunity/promises ${VERSION_NUMBER}
#const PROMISES_DEBUG = false
namespace promises
' Create a new promise
function create() as dynamic
'create a unique ID for this promise
id = "promise-" + promises.internal.createUuid()
#if PROMISES_DEBUG
' debugging the promise flow
if m.__promises__idSequence = invalid then
m.__promises__idSequence = 0
end if
m.__promises__idSequence++
id = "promise-" + m.__promises__idSequence.ToStr()
#end if
#if PROMISES_DEBUG
print "[promises.create]", id
#end if
node = createObject("roSGNode", "Promise")
node.id = id
return node
end function
' TODO rename this to `then` once BrighterScript supports using keywords as namespaced function names
function onThen(promise as dynamic, callback as function, context = "__INVALID__" as object) as dynamic
return promises.internal.on("then", promise, callback, context)
end function
' TODO rename this to `catch` once BrighterScript supports using keywords as namespaced function names
function onCatch(promise as dynamic, callback as function, context = "__INVALID__" as object) as dynamic
return promises.internal.on("catch", promise, callback, context)
end function
' TODO rename this to `finally` once BrighterScript supports using keywords as namespaced function names
function onFinally(promise as dynamic, callback as function, context = "__INVALID__" as object) as dynamic
return promises.internal.on("finally", promise, callback, context)
end function
' Allows multiple promise operations to be resolved as a single promise.
function all(promiseArray as dynamic) as dynamic
' Create a deferred to be resolved later
deferred = promises.create()
if type(promiseArray) = "roArray" and not promiseArray.isEmpty() then
' Track the state and results of all the promises
state = {
deferred: deferred
results: []
resolvedCount: 0
total: promiseArray.count()
done: false
}
for i = 0 to promiseArray.count() - 1
promise = promiseArray[i]
if promises.isPromise(promise) then
' Watch for both resolved or rejected promises
promises.onThen(promise, sub(result as dynamic, context as dynamic)
' Do not process any promises that come in late
' This can happen if any of the other promises reject
if not context.state.done then
' Always assign the result to the origin index so results are in the same
' order as the supplied promiseArray
context.state.results[context.index] = result
context.state.resolvedCount++
if context.state.resolvedCount = context.state.total then
' All the promises are resolved.
' Resolve the deferred and make the state as complete
context.state.done = true
promises.resolve(context.state.results, context.state.deferred)
end if
end if
end sub, { state: state, index: i })
promises.onCatch(promise, sub(error as dynamic, state as dynamic)
' This shouldn't happen but if we somehow get a rejected promise after
' the state is marked as done we should ignore this callback
if not state.done then
' Immediately mark the state as done and reject the deferred
' with the error from the rejected promise the first time any
' promise rejects regardless where in the promise array it was
' located.
state.done = true
promises.reject(error, state.deferred)
end if
end sub, state)
else
' The value in the promise array is not a promise.
' Immediately set the result.
state.results[i] = promise
state.resolvedCount++
if state.resolvedCount = state.total then
' All the promises are resolved.
' Resolve the deferred and make the state as complete
state.done = true
promises.resolve(state.results, state.deferred)
end if
end if
end for
else
if type(promiseArray) = "roArray" then
' Resolve when the array is empty
promises.resolve(promiseArray, deferred)
else
' Reject if the supplied list is not an array
promises.reject("Promises.all: did not supply an array")
end if
end if
return deferred
end function
function resolve(result as dynamic, promise = invalid as dynamic) as object
if not promises.isPromise(promise) then
promise = promises.create()
end if
if not promises.isComplete(promise) then
' console.trace("[promises.resolve]", promise.id)
promise.update({ promiseResult: result }, true)
promise.promiseState = promises.internal.PromiseState.resolved
end if
return promise
end function
function reject(error as dynamic, promise = invalid as dynamic) as object
if not promises.isPromise(promise) then
promise = promises.create()
end if
if not promises.isComplete(promise) then
' console.trace("[promises.reject]", promise.id)
promise.update({ promiseResult: error }, true)
promise.promiseState = promises.internal.PromiseState.rejected
end if
return promise
end function
function isComplete(promise as object) as boolean
return promises.isPromise(promise) and (promise.promiseState = promises.internal.PromiseState.resolved or promise.promiseState = promises.internal.PromiseState.rejected)
end function
' Determines if the given item is a promise.
'
' Will return true if at least one of the following conditions are true:
' - the SubType exactly equals "Promise"
' - the subtype ends with "_promise" case insensitive
' - the node has a field called "promiseState"
function isPromise(promise as dynamic) as boolean
if not type(promise) = "roSGNode" then
return false
end if
subType = lCase(promise.subType())
if subType.endsWith("_promise") then
return true
end if
if subType = "promise" then
return true
end if
while true
subType = promise.parentSubtype(subType)
if lCase(subType).endsWith("_promise") then return true
if subType = "" then exit while
end while
return promise.hasField(promises.internal.PromiseField.promiseState)
end function
' Remove all promise storage from the current m
sub clean()
for each key in m
if key.startsWith("__promises__") then
m.delete(key)
end if
end for
end sub
'Allows chaining multiple promise operations in a row in a clean syntax
function chain(initialPromise as object, context = "__INVALID__" as object) as object
return {
_lastPromise: initialPromise
_context: context
then: function(callback as function) as object
m._lastPromise = promises.onThen(m._lastPromise, callback, m._context)
return m
end function
"catch": function(callback as function) as object
m._lastPromise = promises.onCatch(m._lastPromise, callback, m._context)
return m
end function
finally: function(callback as function) as object
m._lastPromise = promises.onFinally(m._lastPromise, callback, m._context)
return m
end function
toPromise: function() as object
return m._lastPromise
end function
}
end function
' Makes sure the value supplied is a promise
function ensurePromise(value as object) as object
if promises.isPromise(value) then return value
return promises.resolve(value)
end function
end namespace
namespace promises.internal
enum PromiseState
pending = "pending"
resolved = "resolved"
rejected = "rejected"
end enum
enum PromiseField
promiseState = "promiseState"
promiseResult = "promiseResult"
end enum
' Clear storage for a given promise
sub clearPromiseStorage(promise as object)
m.delete("__promises__" + promise.id)
end sub
' Get the storage for a promise on `m`
function getPromiseStorage(promise as object) as object
id = "__promises__" + promise.id
storage = m[id]
if storage = invalid then
' unregister any observers on the promise to prevent multiple callbacks
promises.internal.unobserveFieldScoped(promise, promises.internal.PromiseField.promiseState)
promises.internal.observeFieldScoped(promise, promises.internal.PromiseField.promiseState, promises.internal.notifyListeners)
storage = {
promise: promise
thenListeners: []
catchListeners: []
finallyListeners: []
}
m[id] = storage
end if
return storage
end function
'
' Registers a listener for a promise for the then, catch, or finally events
' @param eventName - should be "then", "catch", or "finally"
'
function on(eventName as string, promise as dynamic, callback as function, context = {} as object) as dynamic
if promises.isPromise(promise) then
newPromise = promises.create()
storage = promises.internal.getPromiseStorage(promise)
storage[eventName + "Listeners"].push({
callback: callback
context: context
promise: newPromise
})
promiseState = promise.promiseState
'trigger a change if the promise is already resolved
if promiseState = promises.internal.PromiseState.resolved or promiseState = promises.internal.PromiseState.rejected then
promises.internal.delay(sub (details as object)
details.promise.promiseState = details.promiseState
end sub, { promise: promise, promiseState: promiseState })
end if
#if PROMISES_DEBUG
print "[promises.watch]", newPromise.id, "is watching", promise.id, eventName
#end if
return newPromise
end if
errorMessage = "Cannot register promises." + eventName + " for non-promise"
#if PROMISES_DEBUG
print errorMessage
#end if
throw errorMessage
return invalid
end function
'
' Notify all the listeners of a promise that it has been completed
'
sub notifyListeners(event as object)
originalPromise = event.getRoSgNode()
if promises.isComplete(originalPromise) then
#if PROMISES_DEBUG
print "[promises.done]", originalPromise.id, "has completed"
#end if
' unregister any observers once the promise is completed
promises.internal.unobserveFieldScoped(originalPromise, promises.internal.PromiseField.promiseState)
promiseStorage = promises.internal.getPromiseStorage(originalPromise)
' Delete the storage for this promise since we are going to handled all of the current listeners.
' Any new listeners created as a result of the logic in the callbacks will
' register a new instance of the promise storage item. If a new storage item is created
' we will notify the new listeners when we are done with the current ones.
promises.internal.clearPromiseStorage(originalPromise)
promiseState = originalPromise.promiseState
promiseResult = originalPromise.promiseResult
'handle .then() listeners
for each listener in promiseStorage.thenListeners
promises.internal.processPromiseListener(originalPromise, listener, promiseState = promises.internal.PromiseState.resolved, promiseResult)
end for
'handle .catch() listeners
for each listener in promiseStorage.catchListeners
promises.internal.processPromiseListener(originalPromise, listener, promiseState = promises.internal.PromiseState.rejected, promiseResult)
end for
'handle .finally() listeners
for each listener in promiseStorage.finallyListeners
promises.internal.processPromiseListener(originalPromise, listener, true)
end for
#if PROMISES_DEBUG
if m.__promises__debug = invalid then
m.__promises__debug = []
end if
'TODO giant memory leak. if you see this, delete it immediately!
m.__promises__debug.push(promiseStorage)
#end if
if promises.internal.hasStorage(originalPromise) then
' There were listeners added as a result of some of the callback notifications
' Re-trigger the notification process for the new listeners
promises.internal.delay(sub (event as object)
promises.internal.notifyListeners(event)
end sub, event)
end if
end if
end sub
' Used to check if there is a storage item of listeners for the supplied promise
function hasStorage(promise as dynamic) as boolean
return m.doesExist("__promises__" + promise.id)
end function
' We use an internal value to represent unset. Check if the parameter is that value
function isSet(value as dynamic) as boolean
return not (promises.internal.isNonEmptyString(value) and value = "__INVALID__")
end function
' Is the supplied value a valid String type and is not empty
' @param value - The variable to be checked
' @return true if value is a non-empty string, false otherwise
function isNonEmptyString(value as dynamic) as boolean
return (type(value) = "String" or type(value) = "roString") and value <> ""
end function
' Handle an individual promise listener
sub processPromiseListener(originalPromise as object, storageItem as object, callCallback as boolean, promiseValue = "__INVALID__" as dynamic)
newPromise = storageItem.promise
#if PROMISES_DEBUG
print "[promises.notify]", originalPromise.id, "notifying", newPromise.id
#end if
callback = storageItem.callback
context = storageItem.context
hasContext = promises.internal.isSet(context)
hasPromiseValue = promises.internal.isSet(promiseValue)
'only call the callback if configured to do so
if callCallback then
#if PROMISES_DEBUG
print "[promises.notify]", originalPromise.id, "calling callback for", newPromise.id
#end if
try
'.then and .catch take one or two parameters (`promiseValue` and optional `context`)
if hasPromiseValue then
if hasContext then
callbackResult = callback(promiseValue, context)
else
callbackResult = callback(promiseValue)
end if
'.finally callback takes 1 optional parameter (`context`)
else
if hasContext then
callbackResult = callback(context)
else
callbackResult = callback()
end if
end if
catch e
#if PROMISES_DEBUG
print "[promises.notify]", originalPromise.id, "callback for", newPromise.id, "threw exception", e
#end if
'the result is a rejected promise
callbackResult = promises.reject(e)
end try
else
'use the current promise value to pass to the next promise (this is a .catch handler)
if originalPromise.promiseState = promises.internal.PromiseState.rejected then
callbackResult = promises.reject(promiseValue)
else
callbackResult = promiseValue
end if
end if
'if the .then() callback returned a promise. wait for it to resolve and THEN resolve the newPromise
if promises.isPromise(callbackResult) then
callbackPromise = callbackResult
'wait for the callback promise to complete
promises.onFinally(callbackPromise, sub (context as object)
promiseState = context.callbackPromise.promiseState
promiseResult = context.callbackPromise.promiseResult
if promiseState = promises.internal.PromiseState.resolved then
'the callback promise is complete. resolve the newPromise
promises.resolve(promiseResult, context.newPromise)
return
end if
if promiseState = promises.internal.PromiseState.rejected then
promises.reject(promiseResult, context.newPromise)
return
end if
end sub, {
newPromise: newPromise
callbackPromise: callbackPromise
})
'the .then() callback returned a non-promise. Resolve the newPromise immediately with this value
else
promises.resolve(callbackResult, newPromise)
end if
end sub
'
' Generates a new UUID
'
function createUuid() as string
if m.__promises__deviceInfo = invalid then
m.__promises__deviceInfo = createObject("roDeviceInfo")
end if
return m.__promises__deviceInfo.getRandomUUID()
end function
' Makes a delayed call to the supplied function. Default behavior is essentially next tick.
' @param {Function} callback - The function to be called after a set delay
' @param {Dynamic} context - a single item of data to be passed into the callback when invoked
' @param {Float} [duration] - the amount of delay before invoking the callback
sub delay(callback as function, context as dynamic, duration = 0.0001 as float)
timer = createObject("roSGNode", "Timer")
timer.update({ duration: duration, repeat: false, id: "__delay_" + promises.internal.createUuid() }, true)
m[timer.id] = {
timer: timer
callback: callback
context: context
}
promises.internal.observeFieldScoped(timer, "fire", sub (event as object)
promises.internal.unobserveFieldScoped(event.getRosgNode(), "fire")
delayId = event.getNode()
options = m[delayId]
callback = options.callback
try
callback(options.context)
catch e
#if PROMISES_DEBUG
print "Crash during utils.delay:", e
#end if
end try
m[delayId] = invalid
end sub)
timer.control = "start"
end sub
' Observes a node field using observeFieldScoped
' @param {roSGNode} node - The node to apply the observer
' @param {String} field - The name of the field to be monitored.
' @param {Dynamic} callback - The name or message port to be executed when the value of the field changes.
' @return true if field could be observed, false if not
function observeFieldScoped(node as object, field as string, callback as dynamic, infoFields = [] as object)
if not type(node) = "roSGNode" then
return false
else
if type(callback) = "roFunction" or type(callback) = "Function" then
callback = callback.toStr().tokenize(" ").peek()
end if
if not node.observeFieldScoped(field, callback, infoFields) then
return false
end if
end if
return true
end function
' Unobserve a node field using unobserveFieldScoped
' @param {roSGNode} node - The node to remove the observer from
' @param {String} field - The name of the field to no longer be monitored.
' @return true if field could be unobserved, false if not
function unobserveFieldScoped(node as object, field as string)
if not type(node) = "roSGNode" then
return false
else
if not node.unobserveFieldScoped(field) then
return false
end if
end if
return true
end function
end namespace