@isentinel/jest-roblox 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2006 @@
1
+ --[[
2
+ An implementation of Promises similar to Promise/A+.
3
+ ]]
4
+
5
+ local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s"
6
+ local ERROR_NON_LIST = "Please pass a list of promises to %s"
7
+ local ERROR_NON_FUNCTION = "Please pass a handler function to %s!"
8
+ local MODE_KEY_METATABLE = { __mode = "k" }
9
+
10
+ local function isCallable(value)
11
+ if type(value) == "function" then
12
+ return true
13
+ end
14
+
15
+ if type(value) == "table" then
16
+ local metatable = getmetatable(value)
17
+ if metatable and type(rawget(metatable, "__call")) == "function" then
18
+ return true
19
+ end
20
+ end
21
+
22
+ return false
23
+ end
24
+
25
+ --[[
26
+ Creates an enum dictionary with some metamethods to prevent common mistakes.
27
+ ]]
28
+ local function makeEnum(enumName, members)
29
+ local enum = {}
30
+
31
+ for _, memberName in ipairs(members) do
32
+ enum[memberName] = memberName
33
+ end
34
+
35
+ return setmetatable(enum, {
36
+ __index = function(_, k)
37
+ error(string.format("%s is not in %s!", k, enumName), 2)
38
+ end,
39
+ __newindex = function()
40
+ error(string.format("Creating new members in %s is not allowed!", enumName), 2)
41
+ end,
42
+ })
43
+ end
44
+
45
+ --[=[
46
+ An object to represent runtime errors that occur during execution.
47
+ Promises that experience an error like this will be rejected with
48
+ an instance of this object.
49
+
50
+ @class Error
51
+ ]=]
52
+ local Error
53
+ do
54
+ Error = {
55
+ Kind = makeEnum("Promise.Error.Kind", {
56
+ "ExecutionError",
57
+ "AlreadyCancelled",
58
+ "NotResolvedInTime",
59
+ "TimedOut",
60
+ }),
61
+ }
62
+ Error.__index = Error
63
+
64
+ function Error.new(options, parent)
65
+ options = options or {}
66
+ return setmetatable({
67
+ error = tostring(options.error) or "[This error has no error text.]",
68
+ trace = options.trace,
69
+ context = options.context,
70
+ kind = options.kind,
71
+ parent = parent,
72
+ createdTick = os.clock(),
73
+ createdTrace = debug.traceback(),
74
+ }, Error)
75
+ end
76
+
77
+ function Error.is(anything)
78
+ if type(anything) == "table" then
79
+ local metatable = getmetatable(anything)
80
+
81
+ if type(metatable) == "table" then
82
+ return rawget(anything, "error") ~= nil
83
+ and type(rawget(metatable, "extend")) == "function"
84
+ end
85
+ end
86
+
87
+ return false
88
+ end
89
+
90
+ function Error.isKind(anything, kind)
91
+ assert(kind ~= nil, "Argument #2 to Promise.Error.isKind must not be nil")
92
+
93
+ return Error.is(anything) and anything.kind == kind
94
+ end
95
+
96
+ function Error:extend(options)
97
+ options = options or {}
98
+
99
+ options.kind = options.kind or self.kind
100
+
101
+ return Error.new(options, self)
102
+ end
103
+
104
+ function Error:getErrorChain()
105
+ local runtimeErrors = { self }
106
+
107
+ while runtimeErrors[#runtimeErrors].parent do
108
+ table.insert(runtimeErrors, runtimeErrors[#runtimeErrors].parent)
109
+ end
110
+
111
+ return runtimeErrors
112
+ end
113
+
114
+ function Error:__tostring()
115
+ local errorStrings = {
116
+ string.format("-- Promise.Error(%s) --", self.kind or "?"),
117
+ }
118
+
119
+ for _, runtimeError in ipairs(self:getErrorChain()) do
120
+ table.insert(
121
+ errorStrings,
122
+ table.concat({
123
+ runtimeError.trace or runtimeError.error,
124
+ runtimeError.context,
125
+ }, "\n")
126
+ )
127
+ end
128
+
129
+ return table.concat(errorStrings, "\n")
130
+ end
131
+ end
132
+
133
+ --[[
134
+ Packs a number of arguments into a table and returns its length.
135
+
136
+ Used to cajole varargs without dropping sparse values.
137
+ ]]
138
+ local function pack(...)
139
+ return select("#", ...), { ... }
140
+ end
141
+
142
+ --[[
143
+ Returns first value (success), and packs all following values.
144
+ ]]
145
+ local function packResult(success, ...)
146
+ return success, select("#", ...), { ... }
147
+ end
148
+
149
+ local function makeErrorHandler(traceback)
150
+ assert(traceback ~= nil, "traceback is nil")
151
+
152
+ return function(err)
153
+ -- If the error object is already a table, forward it directly.
154
+ -- Should we extend the error here and add our own trace?
155
+
156
+ if type(err) == "table" then
157
+ return err
158
+ end
159
+
160
+ return Error.new({
161
+ error = err,
162
+ kind = Error.Kind.ExecutionError,
163
+ trace = debug.traceback(tostring(err), 2),
164
+ context = "Promise created at:\n\n" .. traceback,
165
+ })
166
+ end
167
+ end
168
+
169
+ --[[
170
+ Calls a Promise executor with error handling.
171
+ ]]
172
+ local function runExecutor(traceback, callback, ...)
173
+ return packResult(xpcall(callback, makeErrorHandler(traceback), ...))
174
+ end
175
+
176
+ --[[
177
+ Creates a function that invokes a callback with correct error handling and
178
+ resolution mechanisms.
179
+ ]]
180
+ local function createAdvancer(traceback, callback, resolve, reject)
181
+ return function(...)
182
+ local ok, resultLength, result = runExecutor(traceback, callback, ...)
183
+
184
+ if ok then
185
+ resolve(unpack(result, 1, resultLength))
186
+ else
187
+ reject(result[1])
188
+ end
189
+ end
190
+ end
191
+
192
+ local function isEmpty(t)
193
+ return next(t) == nil
194
+ end
195
+
196
+ --[=[
197
+ An enum value used to represent the Promise's status.
198
+ @interface Status
199
+ @tag enum
200
+ @within Promise
201
+ .Started "Started" -- The Promise is executing, and not settled yet.
202
+ .Resolved "Resolved" -- The Promise finished successfully.
203
+ .Rejected "Rejected" -- The Promise was rejected.
204
+ .Cancelled "Cancelled" -- The Promise was cancelled before it finished.
205
+ ]=]
206
+ --[=[
207
+ @prop Status Status
208
+ @within Promise
209
+ @readonly
210
+ @tag enums
211
+ A table containing all members of the `Status` enum, e.g., `Promise.Status.Resolved`.
212
+ ]=]
213
+ --[=[
214
+ A Promise is an object that represents a value that will exist in the future, but doesn't right now.
215
+ Promises allow you to then attach callbacks that can run once the value becomes available (known as *resolving*),
216
+ or if an error has occurred (known as *rejecting*).
217
+
218
+ @class Promise
219
+ @__index prototype
220
+ ]=]
221
+ local Promise = {
222
+ Error = Error,
223
+ Status = makeEnum("Promise.Status", { "Started", "Resolved", "Rejected", "Cancelled" }),
224
+ _getTime = os.clock,
225
+ _timeEvent = game:GetService("RunService").Heartbeat,
226
+ _unhandledRejectionCallbacks = {},
227
+ }
228
+ Promise.prototype = {}
229
+ Promise.__index = Promise.prototype
230
+
231
+ function Promise._new(traceback, callback, parent)
232
+ if parent ~= nil and not Promise.is(parent) then
233
+ error("Argument #2 to Promise.new must be a promise or nil", 2)
234
+ end
235
+
236
+ local self = {
237
+ -- The executor thread.
238
+ _thread = nil,
239
+
240
+ -- Used to locate where a promise was created
241
+ _source = traceback,
242
+
243
+ _status = Promise.Status.Started,
244
+
245
+ -- A table containing a list of all results, whether success or failure.
246
+ -- Only valid if _status is set to something besides Started
247
+ _values = nil,
248
+
249
+ -- Lua doesn't like sparse arrays very much, so we explicitly store the
250
+ -- length of _values to handle middle nils.
251
+ _valuesLength = -1,
252
+
253
+ -- Tracks if this Promise has no error observers..
254
+ _unhandledRejection = true,
255
+
256
+ -- Queues representing functions we should invoke when we update!
257
+ _queuedResolve = {},
258
+ _queuedReject = {},
259
+ _queuedFinally = {},
260
+
261
+ -- The function to run when/if this promise is cancelled.
262
+ _cancellationHook = nil,
263
+
264
+ -- The "parent" of this promise in a promise chain. Required for
265
+ -- cancellation propagation upstream.
266
+ _parent = parent,
267
+
268
+ -- Consumers are Promises that have chained onto this one.
269
+ -- We track them for cancellation propagation downstream.
270
+ _consumers = setmetatable({}, MODE_KEY_METATABLE),
271
+ }
272
+
273
+ if parent and parent._status == Promise.Status.Started then
274
+ parent._consumers[self] = true
275
+ end
276
+
277
+ setmetatable(self, Promise)
278
+
279
+ local function resolve(...)
280
+ self:_resolve(...)
281
+ end
282
+
283
+ local function reject(...)
284
+ self:_reject(...)
285
+ end
286
+
287
+ local function onCancel(cancellationHook)
288
+ if cancellationHook then
289
+ if self._status == Promise.Status.Cancelled then
290
+ cancellationHook()
291
+ else
292
+ self._cancellationHook = cancellationHook
293
+ end
294
+ end
295
+
296
+ return self._status == Promise.Status.Cancelled
297
+ end
298
+
299
+ self._thread = coroutine.create(function()
300
+ local ok, _, result = runExecutor(self._source, callback, resolve, reject, onCancel)
301
+
302
+ if not ok then
303
+ reject(result[1])
304
+ end
305
+ end)
306
+
307
+ task.spawn(self._thread)
308
+
309
+ return self
310
+ end
311
+
312
+ --[=[
313
+ Construct a new Promise that will be resolved or rejected with the given callbacks.
314
+
315
+ If you `resolve` with a Promise, it will be chained onto.
316
+
317
+ You can safely yield within the executor function and it will not block the creating thread.
318
+
319
+ ```lua
320
+ local myFunction()
321
+ return Promise.new(function(resolve, reject, onCancel)
322
+ wait(1)
323
+ resolve("Hello world!")
324
+ end)
325
+ end
326
+
327
+ myFunction():andThen(print)
328
+ ```
329
+
330
+ You do not need to use `pcall` within a Promise. Errors that occur during execution will be caught and turned into a rejection automatically. If `error()` is called with a table, that table will be the rejection value. Otherwise, string errors will be converted into `Promise.Error(Promise.Error.Kind.ExecutionError)` objects for tracking debug information.
331
+
332
+ You may register an optional cancellation hook by using the `onCancel` argument:
333
+
334
+ * This should be used to abort any ongoing operations leading up to the promise being settled.
335
+ * Call the `onCancel` function with a function callback as its only argument to set a hook which will in turn be called when/if the promise is cancelled.
336
+ * `onCancel` returns `true` if the Promise was already cancelled when you called `onCancel`.
337
+ * Calling `onCancel` with no argument will not override a previously set cancellation hook, but it will still return `true` if the Promise is currently cancelled.
338
+ * You can set the cancellation hook at any time before resolving.
339
+ * When a promise is cancelled, calls to `resolve` or `reject` will be ignored, regardless of if you set a cancellation hook or not.
340
+
341
+ :::caution
342
+ If the Promise is cancelled, the `executor` thread is closed with `coroutine.close` after the cancellation hook is called.
343
+
344
+ You must perform any cleanup code in the cancellation hook: any time your executor yields, it **may never resume**.
345
+ :::
346
+
347
+ @param executor (resolve: (...: any) -> (), reject: (...: any) -> (), onCancel: (abortHandler?: () -> ()) -> boolean) -> ()
348
+ @return Promise
349
+ ]=]
350
+ function Promise.new(executor)
351
+ return Promise._new(debug.traceback(nil, 2), executor)
352
+ end
353
+
354
+ function Promise:__tostring()
355
+ return string.format("Promise(%s)", self._status)
356
+ end
357
+
358
+ --[=[
359
+ The same as [Promise.new](/api/Promise#new), except execution begins after the next `Heartbeat` event.
360
+
361
+ This is a spiritual replacement for `spawn`, but it does not suffer from the same [issues](https://eryn.io/gist/3db84579866c099cdd5bb2ff37947cec) as `spawn`.
362
+
363
+ ```lua
364
+ local function waitForChild(instance, childName, timeout)
365
+ return Promise.defer(function(resolve, reject)
366
+ local child = instance:WaitForChild(childName, timeout)
367
+
368
+ ;(child and resolve or reject)(child)
369
+ end)
370
+ end
371
+ ```
372
+
373
+ @param executor (resolve: (...: any) -> (), reject: (...: any) -> (), onCancel: (abortHandler?: () -> ()) -> boolean) -> ()
374
+ @return Promise
375
+ ]=]
376
+ function Promise.defer(executor)
377
+ local traceback = debug.traceback(nil, 2)
378
+ local promise
379
+ promise = Promise._new(traceback, function(resolve, reject, onCancel)
380
+ task.defer(function()
381
+ local ok, _, result = runExecutor(traceback, executor, resolve, reject, onCancel)
382
+
383
+ if not ok then
384
+ reject(result[1])
385
+ end
386
+ end)
387
+ end)
388
+
389
+ return promise
390
+ end
391
+
392
+ -- Backwards compatibility
393
+ Promise.async = Promise.defer
394
+
395
+ --[=[
396
+ Creates an immediately resolved Promise with the given value.
397
+
398
+ ```lua
399
+ -- Example using Promise.resolve to deliver cached values:
400
+ function getSomething(name)
401
+ if cache[name] then
402
+ return Promise.resolve(cache[name])
403
+ else
404
+ return Promise.new(function(resolve, reject)
405
+ local thing = getTheThing()
406
+ cache[name] = thing
407
+
408
+ resolve(thing)
409
+ end)
410
+ end
411
+ end
412
+ ```
413
+
414
+ @param ... any
415
+ @return Promise<...any>
416
+ ]=]
417
+ function Promise.resolve(...)
418
+ local length, values = pack(...)
419
+ return Promise._new(debug.traceback(nil, 2), function(resolve)
420
+ resolve(unpack(values, 1, length))
421
+ end)
422
+ end
423
+
424
+ --[=[
425
+ Creates an immediately rejected Promise with the given value.
426
+
427
+ :::caution
428
+ Something needs to consume this rejection (i.e. `:catch()` it), otherwise it will emit an unhandled Promise rejection warning on the next frame. Thus, you should not create and store rejected Promises for later use. Only create them on-demand as needed.
429
+ :::
430
+
431
+ @param ... any
432
+ @return Promise<...any>
433
+ ]=]
434
+ function Promise.reject(...)
435
+ local length, values = pack(...)
436
+ return Promise._new(debug.traceback(nil, 2), function(_, reject)
437
+ reject(unpack(values, 1, length))
438
+ end)
439
+ end
440
+
441
+ --[[
442
+ Runs a non-promise-returning function as a Promise with the
443
+ given arguments.
444
+ ]]
445
+ function Promise._try(traceback, callback, ...)
446
+ local valuesLength, values = pack(...)
447
+
448
+ return Promise._new(traceback, function(resolve)
449
+ resolve(callback(unpack(values, 1, valuesLength)))
450
+ end)
451
+ end
452
+
453
+ --[=[
454
+ Begins a Promise chain, calling a function and returning a Promise resolving with its return value. If the function errors, the returned Promise will be rejected with the error. You can safely yield within the Promise.try callback.
455
+
456
+ :::info
457
+ `Promise.try` is similar to [Promise.promisify](#promisify), except the callback is invoked immediately instead of returning a new function.
458
+ :::
459
+
460
+ ```lua
461
+ Promise.try(function()
462
+ return math.random(1, 2) == 1 and "ok" or error("Oh an error!")
463
+ end)
464
+ :andThen(function(text)
465
+ print(text)
466
+ end)
467
+ :catch(function(err)
468
+ warn("Something went wrong")
469
+ end)
470
+ ```
471
+
472
+ @param callback (...: T...) -> ...any
473
+ @param ... T... -- Additional arguments passed to `callback`
474
+ @return Promise
475
+ ]=]
476
+ function Promise.try(callback, ...)
477
+ return Promise._try(debug.traceback(nil, 2), callback, ...)
478
+ end
479
+
480
+ --[[
481
+ Returns a new promise that:
482
+ * is resolved when all input promises resolve
483
+ * is rejected if ANY input promises reject
484
+ ]]
485
+ function Promise._all(traceback, promises, amount)
486
+ if type(promises) ~= "table" then
487
+ error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
488
+ end
489
+
490
+ -- We need to check that each value is a promise here so that we can produce
491
+ -- a proper error rather than a rejected promise with our error.
492
+ for i, promise in pairs(promises) do
493
+ if not Promise.is(promise) then
494
+ error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
495
+ end
496
+ end
497
+
498
+ -- If there are no values then return an already resolved promise.
499
+ if #promises == 0 or amount == 0 then
500
+ return Promise.resolve({})
501
+ end
502
+
503
+ return Promise._new(traceback, function(resolve, reject, onCancel)
504
+ -- An array to contain our resolved values from the given promises.
505
+ local resolvedValues = {}
506
+ local newPromises = {}
507
+
508
+ -- Keep a count of resolved promises because just checking the resolved
509
+ -- values length wouldn't account for promises that resolve with nil.
510
+ local resolvedCount = 0
511
+ local rejectedCount = 0
512
+ local done = false
513
+
514
+ local function cancel()
515
+ for _, promise in ipairs(newPromises) do
516
+ promise:cancel()
517
+ end
518
+ end
519
+
520
+ -- Called when a single value is resolved and resolves if all are done.
521
+ local function resolveOne(i, ...)
522
+ if done then
523
+ return
524
+ end
525
+
526
+ resolvedCount = resolvedCount + 1
527
+
528
+ if amount == nil then
529
+ resolvedValues[i] = ...
530
+ else
531
+ resolvedValues[resolvedCount] = ...
532
+ end
533
+
534
+ if resolvedCount >= (amount or #promises) then
535
+ done = true
536
+ resolve(resolvedValues)
537
+ cancel()
538
+ end
539
+ end
540
+
541
+ onCancel(cancel)
542
+
543
+ -- We can assume the values inside `promises` are all promises since we
544
+ -- checked above.
545
+ for i, promise in ipairs(promises) do
546
+ newPromises[i] = promise:andThen(function(...)
547
+ resolveOne(i, ...)
548
+ end, function(...)
549
+ rejectedCount = rejectedCount + 1
550
+
551
+ if amount == nil or #promises - rejectedCount < amount then
552
+ cancel()
553
+ done = true
554
+
555
+ reject(...)
556
+ end
557
+ end)
558
+ end
559
+
560
+ if done then
561
+ cancel()
562
+ end
563
+ end)
564
+ end
565
+
566
+ --[=[
567
+ Accepts an array of Promises and returns a new promise that:
568
+ * is resolved after all input promises resolve.
569
+ * is rejected if *any* input promises reject.
570
+
571
+ :::info
572
+ Only the first return value from each promise will be present in the resulting array.
573
+ :::
574
+
575
+ After any input Promise rejects, all other input Promises that are still pending will be cancelled if they have no other consumers.
576
+
577
+ ```lua
578
+ local promises = {
579
+ returnsAPromise("example 1"),
580
+ returnsAPromise("example 2"),
581
+ returnsAPromise("example 3"),
582
+ }
583
+
584
+ return Promise.all(promises)
585
+ ```
586
+
587
+ @param promises {Promise<T>}
588
+ @return Promise<{T}>
589
+ ]=]
590
+ function Promise.all(promises)
591
+ return Promise._all(debug.traceback(nil, 2), promises)
592
+ end
593
+
594
+ --[=[
595
+ Folds an array of values or promises into a single value. The array is traversed sequentially.
596
+
597
+ The reducer function can return a promise or value directly. Each iteration receives the resolved value from the previous, and the first receives your defined initial value.
598
+
599
+ The folding will stop at the first rejection encountered.
600
+ ```lua
601
+ local basket = {"blueberry", "melon", "pear", "melon"}
602
+ Promise.fold(basket, function(cost, fruit)
603
+ if fruit == "blueberry" then
604
+ return cost -- blueberries are free!
605
+ else
606
+ -- call a function that returns a promise with the fruit price
607
+ return fetchPrice(fruit):andThen(function(fruitCost)
608
+ return cost + fruitCost
609
+ end)
610
+ end
611
+ end, 0)
612
+ ```
613
+
614
+ @since v3.1.0
615
+ @param list {T | Promise<T>}
616
+ @param reducer (accumulator: U, value: T, index: number) -> U | Promise<U>
617
+ @param initialValue U
618
+ ]=]
619
+ function Promise.fold(list, reducer, initialValue)
620
+ assert(type(list) == "table", "Bad argument #1 to Promise.fold: must be a table")
621
+ assert(isCallable(reducer), "Bad argument #2 to Promise.fold: must be a function")
622
+
623
+ local accumulator = Promise.resolve(initialValue)
624
+ return Promise.each(list, function(resolvedElement, i)
625
+ accumulator = accumulator:andThen(function(previousValueResolved)
626
+ return reducer(previousValueResolved, resolvedElement, i)
627
+ end)
628
+ end):andThen(function()
629
+ return accumulator
630
+ end)
631
+ end
632
+
633
+ --[=[
634
+ Accepts an array of Promises and returns a Promise that is resolved as soon as `count` Promises are resolved from the input array. The resolved array values are in the order that the Promises resolved in. When this Promise resolves, all other pending Promises are cancelled if they have no other consumers.
635
+
636
+ `count` 0 results in an empty array. The resultant array will never have more than `count` elements.
637
+
638
+ ```lua
639
+ local promises = {
640
+ returnsAPromise("example 1"),
641
+ returnsAPromise("example 2"),
642
+ returnsAPromise("example 3"),
643
+ }
644
+
645
+ return Promise.some(promises, 2) -- Only resolves with first 2 promises to resolve
646
+ ```
647
+
648
+ @param promises {Promise<T>}
649
+ @param count number
650
+ @return Promise<{T}>
651
+ ]=]
652
+ function Promise.some(promises, count)
653
+ assert(type(count) == "number", "Bad argument #2 to Promise.some: must be a number")
654
+
655
+ return Promise._all(debug.traceback(nil, 2), promises, count)
656
+ end
657
+
658
+ --[=[
659
+ Accepts an array of Promises and returns a Promise that is resolved as soon as *any* of the input Promises resolves. It will reject only if *all* input Promises reject. As soon as one Promises resolves, all other pending Promises are cancelled if they have no other consumers.
660
+
661
+ Resolves directly with the value of the first resolved Promise. This is essentially [[Promise.some]] with `1` count, except the Promise resolves with the value directly instead of an array with one element.
662
+
663
+ ```lua
664
+ local promises = {
665
+ returnsAPromise("example 1"),
666
+ returnsAPromise("example 2"),
667
+ returnsAPromise("example 3"),
668
+ }
669
+
670
+ return Promise.any(promises) -- Resolves with first value to resolve (only rejects if all 3 rejected)
671
+ ```
672
+
673
+ @param promises {Promise<T>}
674
+ @return Promise<T>
675
+ ]=]
676
+ function Promise.any(promises)
677
+ return Promise._all(debug.traceback(nil, 2), promises, 1):andThen(function(values)
678
+ return values[1]
679
+ end)
680
+ end
681
+
682
+ --[=[
683
+ Accepts an array of Promises and returns a new Promise that resolves with an array of in-place Statuses when all input Promises have settled. This is equivalent to mapping `promise:finally` over the array of Promises.
684
+
685
+ ```lua
686
+ local promises = {
687
+ returnsAPromise("example 1"),
688
+ returnsAPromise("example 2"),
689
+ returnsAPromise("example 3"),
690
+ }
691
+
692
+ return Promise.allSettled(promises)
693
+ ```
694
+
695
+ @param promises {Promise<T>}
696
+ @return Promise<{Status}>
697
+ ]=]
698
+ function Promise.allSettled(promises)
699
+ if type(promises) ~= "table" then
700
+ error(string.format(ERROR_NON_LIST, "Promise.allSettled"), 2)
701
+ end
702
+
703
+ -- We need to check that each value is a promise here so that we can produce
704
+ -- a proper error rather than a rejected promise with our error.
705
+ for i, promise in pairs(promises) do
706
+ if not Promise.is(promise) then
707
+ error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.allSettled", tostring(i)), 2)
708
+ end
709
+ end
710
+
711
+ -- If there are no values then return an already resolved promise.
712
+ if #promises == 0 then
713
+ return Promise.resolve({})
714
+ end
715
+
716
+ return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
717
+ -- An array to contain our resolved values from the given promises.
718
+ local fates = {}
719
+ local newPromises = {}
720
+
721
+ -- Keep a count of resolved promises because just checking the resolved
722
+ -- values length wouldn't account for promises that resolve with nil.
723
+ local finishedCount = 0
724
+
725
+ -- Called when a single value is resolved and resolves if all are done.
726
+ local function resolveOne(i, ...)
727
+ finishedCount = finishedCount + 1
728
+
729
+ fates[i] = ...
730
+
731
+ if finishedCount >= #promises then
732
+ resolve(fates)
733
+ end
734
+ end
735
+
736
+ onCancel(function()
737
+ for _, promise in ipairs(newPromises) do
738
+ promise:cancel()
739
+ end
740
+ end)
741
+
742
+ -- We can assume the values inside `promises` are all promises since we
743
+ -- checked above.
744
+ for i, promise in ipairs(promises) do
745
+ newPromises[i] = promise:finally(function(...)
746
+ resolveOne(i, ...)
747
+ end)
748
+ end
749
+ end)
750
+ end
751
+
752
+ --[=[
753
+ Accepts an array of Promises and returns a new promise that is resolved or rejected as soon as any Promise in the array resolves or rejects.
754
+
755
+ :::warning
756
+ If the first Promise to settle from the array settles with a rejection, the resulting Promise from `race` will reject.
757
+
758
+ If you instead want to tolerate rejections, and only care about at least one Promise resolving, you should use [Promise.any](#any) or [Promise.some](#some) instead.
759
+ :::
760
+
761
+ All other Promises that don't win the race will be cancelled if they have no other consumers.
762
+
763
+ ```lua
764
+ local promises = {
765
+ returnsAPromise("example 1"),
766
+ returnsAPromise("example 2"),
767
+ returnsAPromise("example 3"),
768
+ }
769
+
770
+ return Promise.race(promises) -- Only returns 1st value to resolve or reject
771
+ ```
772
+
773
+ @param promises {Promise<T>}
774
+ @return Promise<T>
775
+ ]=]
776
+ function Promise.race(promises)
777
+ assert(type(promises) == "table", string.format(ERROR_NON_LIST, "Promise.race"))
778
+
779
+ for i, promise in pairs(promises) do
780
+ assert(
781
+ Promise.is(promise),
782
+ string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.race", tostring(i))
783
+ )
784
+ end
785
+
786
+ return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
787
+ local newPromises = {}
788
+ local finished = false
789
+
790
+ local function cancel()
791
+ for _, promise in ipairs(newPromises) do
792
+ promise:cancel()
793
+ end
794
+ end
795
+
796
+ local function finalize(callback)
797
+ return function(...)
798
+ cancel()
799
+ finished = true
800
+ return callback(...)
801
+ end
802
+ end
803
+
804
+ if onCancel(finalize(reject)) then
805
+ return
806
+ end
807
+
808
+ for i, promise in ipairs(promises) do
809
+ newPromises[i] = promise:andThen(finalize(resolve), finalize(reject))
810
+ end
811
+
812
+ if finished then
813
+ cancel()
814
+ end
815
+ end)
816
+ end
817
+
818
+ --[=[
819
+ Iterates serially over the given an array of values, calling the predicate callback on each value before continuing.
820
+
821
+ If the predicate returns a Promise, we wait for that Promise to resolve before moving on to the next item
822
+ in the array.
823
+
824
+ :::info
825
+ `Promise.each` is similar to `Promise.all`, except the Promises are ran in order instead of all at once.
826
+
827
+ But because Promises are eager, by the time they are created, they're already running. Thus, we need a way to defer creation of each Promise until a later time.
828
+
829
+ The predicate function exists as a way for us to operate on our data instead of creating a new closure for each Promise. If you would prefer, you can pass in an array of functions, and in the predicate, call the function and return its return value.
830
+ :::
831
+
832
+ ```lua
833
+ Promise.each({
834
+ "foo",
835
+ "bar",
836
+ "baz",
837
+ "qux"
838
+ }, function(value, index)
839
+ return Promise.delay(1):andThen(function()
840
+ print(("%d) Got %s!"):format(index, value))
841
+ end)
842
+ end)
843
+
844
+ --[[
845
+ (1 second passes)
846
+ > 1) Got foo!
847
+ (1 second passes)
848
+ > 2) Got bar!
849
+ (1 second passes)
850
+ > 3) Got baz!
851
+ (1 second passes)
852
+ > 4) Got qux!
853
+ ]]
854
+ ```
855
+
856
+ If the Promise a predicate returns rejects, the Promise from `Promise.each` is also rejected with the same value.
857
+
858
+ If the array of values contains a Promise, when we get to that point in the list, we wait for the Promise to resolve before calling the predicate with the value.
859
+
860
+ If a Promise in the array of values is already Rejected when `Promise.each` is called, `Promise.each` rejects with that value immediately (the predicate callback will never be called even once). If a Promise in the list is already Cancelled when `Promise.each` is called, `Promise.each` rejects with `Promise.Error(Promise.Error.Kind.AlreadyCancelled`). If a Promise in the array of values is Started at first, but later rejects, `Promise.each` will reject with that value and iteration will not continue once iteration encounters that value.
861
+
862
+ Returns a Promise containing an array of the returned/resolved values from the predicate for each item in the array of values.
863
+
864
+ If this Promise returned from `Promise.each` rejects or is cancelled for any reason, the following are true:
865
+ - Iteration will not continue.
866
+ - Any Promises within the array of values will now be cancelled if they have no other consumers.
867
+ - The Promise returned from the currently active predicate will be cancelled if it hasn't resolved yet.
868
+
869
+ @since 3.0.0
870
+ @param list {T | Promise<T>}
871
+ @param predicate (value: T, index: number) -> U | Promise<U>
872
+ @return Promise<{U}>
873
+ ]=]
874
+ function Promise.each(list, predicate)
875
+ assert(type(list) == "table", string.format(ERROR_NON_LIST, "Promise.each"))
876
+ assert(isCallable(predicate), string.format(ERROR_NON_FUNCTION, "Promise.each"))
877
+
878
+ return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
879
+ local results = {}
880
+ local promisesToCancel = {}
881
+
882
+ local cancelled = false
883
+
884
+ local function cancel()
885
+ for _, promiseToCancel in ipairs(promisesToCancel) do
886
+ promiseToCancel:cancel()
887
+ end
888
+ end
889
+
890
+ onCancel(function()
891
+ cancelled = true
892
+
893
+ cancel()
894
+ end)
895
+
896
+ -- We need to preprocess the list of values and look for Promises.
897
+ -- If we find some, we must register our andThen calls now, so that those Promises have a consumer
898
+ -- from us registered. If we don't do this, those Promises might get cancelled by something else
899
+ -- before we get to them in the series because it's not possible to tell that we plan to use it
900
+ -- unless we indicate it here.
901
+
902
+ local preprocessedList = {}
903
+
904
+ for index, value in ipairs(list) do
905
+ if Promise.is(value) then
906
+ if value:getStatus() == Promise.Status.Cancelled then
907
+ cancel()
908
+ return reject(Error.new({
909
+ error = "Promise is cancelled",
910
+ kind = Error.Kind.AlreadyCancelled,
911
+ context = string.format(
912
+ "The Promise that was part of the array at index %d passed into Promise.each was already cancelled when Promise.each began.\n\nThat Promise was created at:\n\n%s",
913
+ index,
914
+ value._source
915
+ ),
916
+ }))
917
+ elseif value:getStatus() == Promise.Status.Rejected then
918
+ cancel()
919
+ return reject(select(2, value:await()))
920
+ end
921
+
922
+ -- Chain a new Promise from this one so we only cancel ours
923
+ local ourPromise = value:andThen(function(...)
924
+ return ...
925
+ end)
926
+
927
+ table.insert(promisesToCancel, ourPromise)
928
+ preprocessedList[index] = ourPromise
929
+ else
930
+ preprocessedList[index] = value
931
+ end
932
+ end
933
+
934
+ for index, value in ipairs(preprocessedList) do
935
+ if Promise.is(value) then
936
+ local success
937
+ success, value = value:await()
938
+
939
+ if not success then
940
+ cancel()
941
+ return reject(value)
942
+ end
943
+ end
944
+
945
+ if cancelled then
946
+ return
947
+ end
948
+
949
+ local predicatePromise = Promise.resolve(predicate(value, index))
950
+
951
+ table.insert(promisesToCancel, predicatePromise)
952
+
953
+ local success, result = predicatePromise:await()
954
+
955
+ if not success then
956
+ cancel()
957
+ return reject(result)
958
+ end
959
+
960
+ results[index] = result
961
+ end
962
+
963
+ resolve(results)
964
+ end)
965
+ end
966
+
967
+ --[=[
968
+ Checks whether the given object is a Promise via duck typing. This only checks if the object is a table and has an `andThen` method.
969
+
970
+ @param object any
971
+ @return boolean -- `true` if the given `object` is a Promise.
972
+ ]=]
973
+ function Promise.is(object)
974
+ if type(object) ~= "table" then
975
+ return false
976
+ end
977
+
978
+ local objectMetatable = getmetatable(object)
979
+
980
+ if objectMetatable == Promise then
981
+ -- The Promise came from this library.
982
+ return true
983
+ elseif objectMetatable == nil then
984
+ -- No metatable, but we should still chain onto tables with andThen methods
985
+ return isCallable(object.andThen)
986
+ elseif
987
+ type(objectMetatable) == "table"
988
+ and type(rawget(objectMetatable, "__index")) == "table"
989
+ and isCallable(rawget(rawget(objectMetatable, "__index"), "andThen"))
990
+ then
991
+ -- Maybe this came from a different or older Promise library.
992
+ return true
993
+ end
994
+
995
+ return false
996
+ end
997
+
998
+ --[=[
999
+ Wraps a function that yields into one that returns a Promise.
1000
+
1001
+ Any errors that occur while executing the function will be turned into rejections.
1002
+
1003
+ :::info
1004
+ `Promise.promisify` is similar to [Promise.try](#try), except the callback is returned as a callable function instead of being invoked immediately.
1005
+ :::
1006
+
1007
+ ```lua
1008
+ local sleep = Promise.promisify(wait)
1009
+
1010
+ sleep(1):andThen(print)
1011
+ ```
1012
+
1013
+ ```lua
1014
+ local isPlayerInGroup = Promise.promisify(function(player, groupId)
1015
+ return player:IsInGroup(groupId)
1016
+ end)
1017
+ ```
1018
+
1019
+ @param callback (...: any) -> ...any
1020
+ @return (...: any) -> Promise
1021
+ ]=]
1022
+ function Promise.promisify(callback)
1023
+ return function(...)
1024
+ return Promise._try(debug.traceback(nil, 2), callback, ...)
1025
+ end
1026
+ end
1027
+
1028
+ --[=[
1029
+ Returns a Promise that resolves after `seconds` seconds have passed. The Promise resolves with the actual amount of time that was waited.
1030
+
1031
+ This function is a wrapper around `task.delay`.
1032
+
1033
+ :::warning
1034
+ Passing NaN, +Infinity, -Infinity, 0, or any other number less than the duration of a Heartbeat will cause the promise to resolve on the very next Heartbeat.
1035
+ :::
1036
+
1037
+ ```lua
1038
+ Promise.delay(5):andThenCall(print, "This prints after 5 seconds")
1039
+ ```
1040
+
1041
+ @function delay
1042
+ @within Promise
1043
+ @param seconds number
1044
+ @return Promise<number>
1045
+ ]=]
1046
+ function Promise.delay(seconds)
1047
+ assert(type(seconds) == "number", "Bad argument #1 to Promise.delay, must be a number.")
1048
+ local startTime = Promise._getTime()
1049
+ return Promise._new(debug.traceback(nil, 2), function(resolve)
1050
+ task.delay(seconds, function()
1051
+ resolve(Promise._getTime() - startTime)
1052
+ end)
1053
+ end)
1054
+ end
1055
+
1056
+ --[=[
1057
+ Returns a new Promise that resolves if the chained Promise resolves within `seconds` seconds, or rejects if execution time exceeds `seconds`. The chained Promise will be cancelled if the timeout is reached.
1058
+
1059
+ Rejects with `rejectionValue` if it is non-nil. If a `rejectionValue` is not given, it will reject with a `Promise.Error(Promise.Error.Kind.TimedOut)`. This can be checked with [[Error.isKind]].
1060
+
1061
+ ```lua
1062
+ getSomething():timeout(5):andThen(function(something)
1063
+ -- got something and it only took at max 5 seconds
1064
+ end):catch(function(e)
1065
+ -- Either getting something failed or the time was exceeded.
1066
+
1067
+ if Promise.Error.isKind(e, Promise.Error.Kind.TimedOut) then
1068
+ warn("Operation timed out!")
1069
+ else
1070
+ warn("Operation encountered an error!")
1071
+ end
1072
+ end)
1073
+ ```
1074
+
1075
+ Sugar for:
1076
+
1077
+ ```lua
1078
+ Promise.race({
1079
+ Promise.delay(seconds):andThen(function()
1080
+ return Promise.reject(
1081
+ rejectionValue == nil
1082
+ and Promise.Error.new({ kind = Promise.Error.Kind.TimedOut })
1083
+ or rejectionValue
1084
+ )
1085
+ end),
1086
+ promise
1087
+ })
1088
+ ```
1089
+
1090
+ @param seconds number
1091
+ @param rejectionValue? any -- The value to reject with if the timeout is reached
1092
+ @return Promise
1093
+ ]=]
1094
+ function Promise.prototype:timeout(seconds, rejectionValue)
1095
+ local traceback = debug.traceback(nil, 2)
1096
+
1097
+ return Promise.race({
1098
+ Promise.delay(seconds):andThen(function()
1099
+ return Promise.reject(rejectionValue == nil and Error.new({
1100
+ kind = Error.Kind.TimedOut,
1101
+ error = "Timed out",
1102
+ context = string.format(
1103
+ "Timeout of %d seconds exceeded.\n:timeout() called at:\n\n%s",
1104
+ seconds,
1105
+ traceback
1106
+ ),
1107
+ }) or rejectionValue)
1108
+ end),
1109
+ self,
1110
+ })
1111
+ end
1112
+
1113
+ --[=[
1114
+ Returns the current Promise status.
1115
+
1116
+ @return Status
1117
+ ]=]
1118
+ function Promise.prototype:getStatus()
1119
+ return self._status
1120
+ end
1121
+
1122
+ --[[
1123
+ Creates a new promise that receives the result of this promise.
1124
+
1125
+ The given callbacks are invoked depending on that result.
1126
+ ]]
1127
+ function Promise.prototype:_andThen(traceback, successHandler, failureHandler)
1128
+ self._unhandledRejection = false
1129
+
1130
+ -- If we are already cancelled, we return a cancelled Promise
1131
+ if self._status == Promise.Status.Cancelled then
1132
+ local promise = Promise.new(function() end)
1133
+ promise:cancel()
1134
+
1135
+ return promise
1136
+ end
1137
+
1138
+ -- Create a new promise to follow this part of the chain
1139
+ return Promise._new(traceback, function(resolve, reject, onCancel)
1140
+ -- Our default callbacks just pass values onto the next promise.
1141
+ -- This lets success and failure cascade correctly!
1142
+
1143
+ local successCallback = resolve
1144
+ if successHandler then
1145
+ successCallback = createAdvancer(traceback, successHandler, resolve, reject)
1146
+ end
1147
+
1148
+ local failureCallback = reject
1149
+ if failureHandler then
1150
+ failureCallback = createAdvancer(traceback, failureHandler, resolve, reject)
1151
+ end
1152
+
1153
+ if self._status == Promise.Status.Started then
1154
+ -- If we haven't resolved yet, put ourselves into the queue
1155
+ table.insert(self._queuedResolve, successCallback)
1156
+ table.insert(self._queuedReject, failureCallback)
1157
+
1158
+ onCancel(function()
1159
+ -- These are guaranteed to exist because the cancellation handler is guaranteed to only
1160
+ -- be called at most once
1161
+ if self._status == Promise.Status.Started then
1162
+ table.remove(
1163
+ self._queuedResolve,
1164
+ table.find(self._queuedResolve, successCallback)
1165
+ )
1166
+ table.remove(
1167
+ self._queuedReject,
1168
+ table.find(self._queuedReject, failureCallback)
1169
+ )
1170
+ end
1171
+ end)
1172
+ elseif self._status == Promise.Status.Resolved then
1173
+ -- This promise has already resolved! Trigger success immediately.
1174
+ successCallback(unpack(self._values, 1, self._valuesLength))
1175
+ elseif self._status == Promise.Status.Rejected then
1176
+ -- This promise died a terrible death! Trigger failure immediately.
1177
+ failureCallback(unpack(self._values, 1, self._valuesLength))
1178
+ end
1179
+ end, self)
1180
+ end
1181
+
1182
+ --[=[
1183
+ Chains onto an existing Promise and returns a new Promise.
1184
+
1185
+ :::warning
1186
+ Within the failure handler, you should never assume that the rejection value is a string. Some rejections within the Promise library are represented by [[Error]] objects. If you want to treat it as a string for debugging, you should call `tostring` on it first.
1187
+ :::
1188
+
1189
+ You can return a Promise from the success or failure handler and it will be chained onto.
1190
+
1191
+ Calling `andThen` on a cancelled Promise returns a cancelled Promise.
1192
+
1193
+ :::tip
1194
+ If the Promise returned by `andThen` is cancelled, `successHandler` and `failureHandler` will not run.
1195
+
1196
+ To run code no matter what, use [Promise:finally].
1197
+ :::
1198
+
1199
+ @param successHandler (...: any) -> ...any
1200
+ @param failureHandler? (...: any) -> ...any
1201
+ @return Promise<...any>
1202
+ ]=]
1203
+ function Promise.prototype:andThen(successHandler, failureHandler)
1204
+ assert(
1205
+ successHandler == nil or isCallable(successHandler),
1206
+ string.format(ERROR_NON_FUNCTION, "Promise:andThen")
1207
+ )
1208
+ assert(
1209
+ failureHandler == nil or isCallable(failureHandler),
1210
+ string.format(ERROR_NON_FUNCTION, "Promise:andThen")
1211
+ )
1212
+
1213
+ return self:_andThen(debug.traceback(nil, 2), successHandler, failureHandler)
1214
+ end
1215
+
1216
+ --[=[
1217
+ Shorthand for `Promise:andThen(nil, failureHandler)`.
1218
+
1219
+ Returns a Promise that resolves if the `failureHandler` worked without encountering an additional error.
1220
+
1221
+ :::warning
1222
+ Within the failure handler, you should never assume that the rejection value is a string. Some rejections within the Promise library are represented by [[Error]] objects. If you want to treat it as a string for debugging, you should call `tostring` on it first.
1223
+ :::
1224
+
1225
+ Calling `catch` on a cancelled Promise returns a cancelled Promise.
1226
+
1227
+ :::tip
1228
+ If the Promise returned by `catch` is cancelled, `failureHandler` will not run.
1229
+
1230
+ To run code no matter what, use [Promise:finally].
1231
+ :::
1232
+
1233
+ @param failureHandler (...: any) -> ...any
1234
+ @return Promise<...any>
1235
+ ]=]
1236
+ function Promise.prototype:catch(failureHandler)
1237
+ assert(
1238
+ failureHandler == nil or isCallable(failureHandler),
1239
+ string.format(ERROR_NON_FUNCTION, "Promise:catch")
1240
+ )
1241
+ return self:_andThen(debug.traceback(nil, 2), nil, failureHandler)
1242
+ end
1243
+
1244
+ --[=[
1245
+ Similar to [Promise.andThen](#andThen), except the return value is the same as the value passed to the handler. In other words, you can insert a `:tap` into a Promise chain without affecting the value that downstream Promises receive.
1246
+
1247
+ ```lua
1248
+ getTheValue()
1249
+ :tap(print)
1250
+ :andThen(function(theValue)
1251
+ print("Got", theValue, "even though print returns nil!")
1252
+ end)
1253
+ ```
1254
+
1255
+ If you return a Promise from the tap handler callback, its value will be discarded but `tap` will still wait until it resolves before passing the original value through.
1256
+
1257
+ @param tapHandler (...: any) -> ...any
1258
+ @return Promise<...any>
1259
+ ]=]
1260
+ function Promise.prototype:tap(tapHandler)
1261
+ assert(isCallable(tapHandler), string.format(ERROR_NON_FUNCTION, "Promise:tap"))
1262
+ return self:_andThen(debug.traceback(nil, 2), function(...)
1263
+ local callbackReturn = tapHandler(...)
1264
+
1265
+ if Promise.is(callbackReturn) then
1266
+ local length, values = pack(...)
1267
+ return callbackReturn:andThen(function()
1268
+ return unpack(values, 1, length)
1269
+ end)
1270
+ end
1271
+
1272
+ return ...
1273
+ end)
1274
+ end
1275
+
1276
+ --[=[
1277
+ Attaches an `andThen` handler to this Promise that calls the given callback with the predefined arguments. The resolved value is discarded.
1278
+
1279
+ ```lua
1280
+ promise:andThenCall(someFunction, "some", "arguments")
1281
+ ```
1282
+
1283
+ This is sugar for
1284
+
1285
+ ```lua
1286
+ promise:andThen(function()
1287
+ return someFunction("some", "arguments")
1288
+ end)
1289
+ ```
1290
+
1291
+ @param callback (...: any) -> any
1292
+ @param ...? any -- Additional arguments which will be passed to `callback`
1293
+ @return Promise
1294
+ ]=]
1295
+ function Promise.prototype:andThenCall(callback, ...)
1296
+ assert(isCallable(callback), string.format(ERROR_NON_FUNCTION, "Promise:andThenCall"))
1297
+ local length, values = pack(...)
1298
+ return self:_andThen(debug.traceback(nil, 2), function()
1299
+ return callback(unpack(values, 1, length))
1300
+ end)
1301
+ end
1302
+
1303
+ --[=[
1304
+ Attaches an `andThen` handler to this Promise that discards the resolved value and returns the given value from it.
1305
+
1306
+ ```lua
1307
+ promise:andThenReturn("some", "values")
1308
+ ```
1309
+
1310
+ This is sugar for
1311
+
1312
+ ```lua
1313
+ promise:andThen(function()
1314
+ return "some", "values"
1315
+ end)
1316
+ ```
1317
+
1318
+ :::caution
1319
+ Promises are eager, so if you pass a Promise to `andThenReturn`, it will begin executing before `andThenReturn` is reached in the chain. Likewise, if you pass a Promise created from [[Promise.reject]] into `andThenReturn`, it's possible that this will trigger the unhandled rejection warning. If you need to return a Promise, it's usually best practice to use [[Promise.andThen]].
1320
+ :::
1321
+
1322
+ @param ... any -- Values to return from the function
1323
+ @return Promise
1324
+ ]=]
1325
+ function Promise.prototype:andThenReturn(...)
1326
+ local length, values = pack(...)
1327
+ return self:_andThen(debug.traceback(nil, 2), function()
1328
+ return unpack(values, 1, length)
1329
+ end)
1330
+ end
1331
+
1332
+ --[=[
1333
+ Cancels this promise, preventing the promise from resolving or rejecting. Does not do anything if the promise is already settled.
1334
+
1335
+ Cancellations will propagate upwards and downwards through chained promises.
1336
+
1337
+ Promises will only be cancelled if all of their consumers are also cancelled. This is to say that if you call `andThen` twice on the same promise, and you cancel only one of the child promises, it will not cancel the parent promise until the other child promise is also cancelled.
1338
+
1339
+ ```lua
1340
+ promise:cancel()
1341
+ ```
1342
+ ]=]
1343
+ function Promise.prototype:cancel()
1344
+ if self._status ~= Promise.Status.Started then
1345
+ return
1346
+ end
1347
+
1348
+ self._status = Promise.Status.Cancelled
1349
+
1350
+ if self._cancellationHook then
1351
+ self._cancellationHook()
1352
+ end
1353
+
1354
+ coroutine.close(self._thread)
1355
+
1356
+ if self._parent then
1357
+ self._parent:_consumerCancelled(self)
1358
+ end
1359
+
1360
+ for child in pairs(self._consumers) do
1361
+ child:cancel()
1362
+ end
1363
+
1364
+ self:_finalize()
1365
+ end
1366
+
1367
+ --[[
1368
+ Used to decrease the number of consumers by 1, and if there are no more,
1369
+ cancel this promise.
1370
+ ]]
1371
+ function Promise.prototype:_consumerCancelled(consumer)
1372
+ if self._status ~= Promise.Status.Started then
1373
+ return
1374
+ end
1375
+
1376
+ self._consumers[consumer] = nil
1377
+
1378
+ if next(self._consumers) == nil then
1379
+ self:cancel()
1380
+ end
1381
+ end
1382
+
1383
+ --[[
1384
+ Used to set a handler for when the promise resolves, rejects, or is
1385
+ cancelled.
1386
+ ]]
1387
+ function Promise.prototype:_finally(traceback, finallyHandler)
1388
+ self._unhandledRejection = false
1389
+
1390
+ local promise = Promise._new(traceback, function(resolve, reject, onCancel)
1391
+ local handlerPromise
1392
+
1393
+ onCancel(function()
1394
+ -- The finally Promise is not a proper consumer of self. We don't care about the resolved value.
1395
+ -- All we care about is running at the end. Therefore, if self has no other consumers, it's safe to
1396
+ -- cancel. We don't need to hold out cancelling just because there's a finally handler.
1397
+ self:_consumerCancelled(self)
1398
+
1399
+ if handlerPromise then
1400
+ handlerPromise:cancel()
1401
+ end
1402
+ end)
1403
+
1404
+ local finallyCallback = resolve
1405
+ if finallyHandler then
1406
+ finallyCallback = function(...)
1407
+ local ok, _, resultList = runExecutor(traceback, finallyHandler, ...)
1408
+ local result = resultList[1]
1409
+ if not ok then
1410
+ return reject(result)
1411
+ end
1412
+
1413
+ if Promise.is(result) then
1414
+ handlerPromise = result
1415
+
1416
+ result
1417
+ :finally(function(status)
1418
+ if status ~= Promise.Status.Rejected then
1419
+ resolve(self)
1420
+ end
1421
+ end)
1422
+ :catch(function(...)
1423
+ reject(...)
1424
+ end)
1425
+ else
1426
+ resolve(self)
1427
+ end
1428
+ end
1429
+ end
1430
+
1431
+ if self._status == Promise.Status.Started then
1432
+ -- The promise is not settled, so queue this.
1433
+ table.insert(self._queuedFinally, finallyCallback)
1434
+ else
1435
+ -- The promise already settled or was cancelled, run the callback now.
1436
+ finallyCallback(self._status)
1437
+ end
1438
+ end)
1439
+
1440
+ return promise
1441
+ end
1442
+
1443
+ --[=[
1444
+ Set a handler that will be called regardless of the promise's fate. The handler is called when the promise is
1445
+ resolved, rejected, *or* cancelled.
1446
+
1447
+ Returns a new Promise that:
1448
+ - resolves with the same values that this Promise resolves with.
1449
+ - rejects with the same values that this Promise rejects with.
1450
+ - is cancelled if this Promise is cancelled.
1451
+
1452
+ If the value you return from the handler is a Promise:
1453
+ - We wait for the Promise to resolve, but we ultimately discard the resolved value.
1454
+ - If the returned Promise rejects, the Promise returned from `finally` will reject with the rejected value from the
1455
+ *returned* promise.
1456
+ - If the `finally` Promise is cancelled, and you returned a Promise from the handler, we cancel that Promise too.
1457
+
1458
+ Otherwise, the return value from the `finally` handler is entirely discarded.
1459
+
1460
+ :::note Cancellation
1461
+ As of Promise v4, `Promise:finally` does not count as a consumer of the parent Promise for cancellation purposes.
1462
+ This means that if all of a Promise's consumers are cancelled and the only remaining callbacks are finally handlers,
1463
+ the Promise is cancelled and the finally callbacks run then and there.
1464
+
1465
+ Cancellation still propagates through the `finally` Promise though: if you cancel the `finally` Promise, it can cancel
1466
+ its parent Promise if it had no other consumers. Likewise, if the parent Promise is cancelled, the `finally` Promise
1467
+ will also be cancelled.
1468
+ :::
1469
+
1470
+ ```lua
1471
+ local thing = createSomething()
1472
+
1473
+ doSomethingWith(thing)
1474
+ :andThen(function()
1475
+ print("It worked!")
1476
+ -- do something..
1477
+ end)
1478
+ :catch(function()
1479
+ warn("Oh no it failed!")
1480
+ end)
1481
+ :finally(function()
1482
+ -- either way, destroy thing
1483
+
1484
+ thing:Destroy()
1485
+ end)
1486
+
1487
+ ```
1488
+
1489
+ @param finallyHandler (status: Status) -> ...any
1490
+ @return Promise<...any>
1491
+ ]=]
1492
+ function Promise.prototype:finally(finallyHandler)
1493
+ assert(
1494
+ finallyHandler == nil or isCallable(finallyHandler),
1495
+ string.format(ERROR_NON_FUNCTION, "Promise:finally")
1496
+ )
1497
+ return self:_finally(debug.traceback(nil, 2), finallyHandler)
1498
+ end
1499
+
1500
+ --[=[
1501
+ Same as `andThenCall`, except for `finally`.
1502
+
1503
+ Attaches a `finally` handler to this Promise that calls the given callback with the predefined arguments.
1504
+
1505
+ @param callback (...: any) -> any
1506
+ @param ...? any -- Additional arguments which will be passed to `callback`
1507
+ @return Promise
1508
+ ]=]
1509
+ function Promise.prototype:finallyCall(callback, ...)
1510
+ assert(isCallable(callback), string.format(ERROR_NON_FUNCTION, "Promise:finallyCall"))
1511
+ local length, values = pack(...)
1512
+ return self:_finally(debug.traceback(nil, 2), function()
1513
+ return callback(unpack(values, 1, length))
1514
+ end)
1515
+ end
1516
+
1517
+ --[=[
1518
+ Attaches a `finally` handler to this Promise that discards the resolved value and returns the given value from it.
1519
+
1520
+ ```lua
1521
+ promise:finallyReturn("some", "values")
1522
+ ```
1523
+
1524
+ This is sugar for
1525
+
1526
+ ```lua
1527
+ promise:finally(function()
1528
+ return "some", "values"
1529
+ end)
1530
+ ```
1531
+
1532
+ @param ... any -- Values to return from the function
1533
+ @return Promise
1534
+ ]=]
1535
+ function Promise.prototype:finallyReturn(...)
1536
+ local length, values = pack(...)
1537
+ return self:_finally(debug.traceback(nil, 2), function()
1538
+ return unpack(values, 1, length)
1539
+ end)
1540
+ end
1541
+
1542
+ --[=[
1543
+ Yields the current thread until the given Promise completes. Returns the Promise's status, followed by the values that the promise resolved or rejected with.
1544
+
1545
+ @yields
1546
+ @return Status -- The Status representing the fate of the Promise
1547
+ @return ...any -- The values the Promise resolved or rejected with.
1548
+ ]=]
1549
+ function Promise.prototype:awaitStatus()
1550
+ self._unhandledRejection = false
1551
+
1552
+ if self._status == Promise.Status.Started then
1553
+ local thread = coroutine.running()
1554
+
1555
+ self
1556
+ :finally(function()
1557
+ task.spawn(thread)
1558
+ end)
1559
+ -- The finally promise can propagate rejections, so we attach a catch handler to prevent the unhandled
1560
+ -- rejection warning from appearing
1561
+ :catch(
1562
+ function() end
1563
+ )
1564
+
1565
+ coroutine.yield()
1566
+ end
1567
+
1568
+ if self._status == Promise.Status.Resolved then
1569
+ return self._status, unpack(self._values, 1, self._valuesLength)
1570
+ elseif self._status == Promise.Status.Rejected then
1571
+ return self._status, unpack(self._values, 1, self._valuesLength)
1572
+ end
1573
+
1574
+ return self._status
1575
+ end
1576
+
1577
+ local function awaitHelper(status, ...)
1578
+ return status == Promise.Status.Resolved, ...
1579
+ end
1580
+
1581
+ --[=[
1582
+ Yields the current thread until the given Promise completes. Returns true if the Promise resolved, followed by the values that the promise resolved or rejected with.
1583
+
1584
+ :::caution
1585
+ If the Promise gets cancelled, this function will return `false`, which is indistinguishable from a rejection. If you need to differentiate, you should use [[Promise.awaitStatus]] instead.
1586
+ :::
1587
+
1588
+ ```lua
1589
+ local worked, value = getTheValue():await()
1590
+
1591
+ if worked then
1592
+ print("got", value)
1593
+ else
1594
+ warn("it failed")
1595
+ end
1596
+ ```
1597
+
1598
+ @yields
1599
+ @return boolean -- `true` if the Promise successfully resolved
1600
+ @return ...any -- The values the Promise resolved or rejected with.
1601
+ ]=]
1602
+ function Promise.prototype:await()
1603
+ return awaitHelper(self:awaitStatus())
1604
+ end
1605
+
1606
+ local function expectHelper(status, ...)
1607
+ if status ~= Promise.Status.Resolved then
1608
+ error((...) == nil and "Expected Promise rejected with no value." or (...), 3)
1609
+ end
1610
+
1611
+ return ...
1612
+ end
1613
+
1614
+ --[=[
1615
+ Yields the current thread until the given Promise completes. Returns the values that the promise resolved with.
1616
+
1617
+ ```lua
1618
+ local worked = pcall(function()
1619
+ print("got", getTheValue():expect())
1620
+ end)
1621
+
1622
+ if not worked then
1623
+ warn("it failed")
1624
+ end
1625
+ ```
1626
+
1627
+ This is essentially sugar for:
1628
+
1629
+ ```lua
1630
+ select(2, assert(promise:await()))
1631
+ ```
1632
+
1633
+ **Errors** if the Promise rejects or gets cancelled.
1634
+
1635
+ @error any -- Errors with the rejection value if this Promise rejects or gets cancelled.
1636
+ @yields
1637
+ @return ...any -- The values the Promise resolved with.
1638
+ ]=]
1639
+ function Promise.prototype:expect()
1640
+ return expectHelper(self:awaitStatus())
1641
+ end
1642
+
1643
+ -- Backwards compatibility
1644
+ Promise.prototype.awaitValue = Promise.prototype.expect
1645
+
1646
+ --[[
1647
+ Intended for use in tests.
1648
+
1649
+ Similar to await(), but instead of yielding if the promise is unresolved,
1650
+ _unwrap will throw. This indicates an assumption that a promise has
1651
+ resolved.
1652
+ ]]
1653
+ function Promise.prototype:_unwrap()
1654
+ if self._status == Promise.Status.Started then
1655
+ error("Promise has not resolved or rejected.", 2)
1656
+ end
1657
+
1658
+ local success = self._status == Promise.Status.Resolved
1659
+
1660
+ return success, unpack(self._values, 1, self._valuesLength)
1661
+ end
1662
+
1663
+ function Promise.prototype:_resolve(...)
1664
+ if self._status ~= Promise.Status.Started then
1665
+ if Promise.is((...)) then
1666
+ (...):_consumerCancelled(self)
1667
+ end
1668
+ return
1669
+ end
1670
+
1671
+ -- If the resolved value was a Promise, we chain onto it!
1672
+ if Promise.is((...)) then
1673
+ -- Without this warning, arguments sometimes mysteriously disappear
1674
+ if select("#", ...) > 1 then
1675
+ local message = string.format(
1676
+ "When returning a Promise from andThen, extra arguments are "
1677
+ .. "discarded! See:\n\n%s",
1678
+ self._source
1679
+ )
1680
+ warn(message)
1681
+ end
1682
+
1683
+ local chainedPromise = ...
1684
+
1685
+ local promise = chainedPromise:andThen(function(...)
1686
+ self:_resolve(...)
1687
+ end, function(...)
1688
+ local maybeRuntimeError = chainedPromise._values[1]
1689
+
1690
+ -- Backwards compatibility < v2
1691
+ if chainedPromise._error then
1692
+ maybeRuntimeError = Error.new({
1693
+ error = chainedPromise._error,
1694
+ kind = Error.Kind.ExecutionError,
1695
+ context = "[No stack trace available as this Promise originated from an older version of the Promise library (< v2)]",
1696
+ })
1697
+ end
1698
+
1699
+ if Error.isKind(maybeRuntimeError, Error.Kind.ExecutionError) then
1700
+ return self:_reject(maybeRuntimeError:extend({
1701
+ error = "This Promise was chained to a Promise that errored.",
1702
+ trace = "",
1703
+ context = string.format(
1704
+ "The Promise at:\n\n%s\n...Rejected because it was chained to the following Promise, which encountered an error:\n",
1705
+ self._source
1706
+ ),
1707
+ }))
1708
+ end
1709
+
1710
+ self:_reject(...)
1711
+ end)
1712
+
1713
+ if promise._status == Promise.Status.Cancelled then
1714
+ self:cancel()
1715
+ elseif promise._status == Promise.Status.Started then
1716
+ -- Adopt ourselves into promise for cancellation propagation.
1717
+ self._parent = promise
1718
+ promise._consumers[self] = true
1719
+ end
1720
+
1721
+ return
1722
+ end
1723
+
1724
+ self._status = Promise.Status.Resolved
1725
+ self._valuesLength, self._values = pack(...)
1726
+
1727
+ -- We assume that these callbacks will not throw errors.
1728
+ for _, callback in ipairs(self._queuedResolve) do
1729
+ coroutine.wrap(callback)(...)
1730
+ end
1731
+
1732
+ self:_finalize()
1733
+ end
1734
+
1735
+ function Promise.prototype:_reject(...)
1736
+ if self._status ~= Promise.Status.Started then
1737
+ return
1738
+ end
1739
+
1740
+ self._status = Promise.Status.Rejected
1741
+ self._valuesLength, self._values = pack(...)
1742
+
1743
+ -- If there are any rejection handlers, call those!
1744
+ if not isEmpty(self._queuedReject) then
1745
+ -- We assume that these callbacks will not throw errors.
1746
+ for _, callback in ipairs(self._queuedReject) do
1747
+ coroutine.wrap(callback)(...)
1748
+ end
1749
+ else
1750
+ -- At this point, no one was able to observe the error.
1751
+ -- An error handler might still be attached if the error occurred
1752
+ -- synchronously. We'll wait one tick, and if there are still no
1753
+ -- observers, then we should put a message in the console.
1754
+
1755
+ local err = tostring((...))
1756
+
1757
+ coroutine.wrap(function()
1758
+ Promise._timeEvent:Wait()
1759
+
1760
+ -- Someone observed the error, hooray!
1761
+ if not self._unhandledRejection then
1762
+ return
1763
+ end
1764
+
1765
+ -- Build a reasonable message
1766
+ local message =
1767
+ string.format("Unhandled Promise rejection:\n\n%s\n\n%s", err, self._source)
1768
+
1769
+ for _, callback in ipairs(Promise._unhandledRejectionCallbacks) do
1770
+ task.spawn(callback, self, unpack(self._values, 1, self._valuesLength))
1771
+ end
1772
+
1773
+ if Promise.TEST then
1774
+ -- Don't spam output when we're running tests.
1775
+ return
1776
+ end
1777
+
1778
+ warn(message)
1779
+ end)()
1780
+ end
1781
+
1782
+ self:_finalize()
1783
+ end
1784
+
1785
+ --[[
1786
+ Calls any :finally handlers. We need this to be a separate method and
1787
+ queue because we must call all of the finally callbacks upon a success,
1788
+ failure, *and* cancellation.
1789
+ ]]
1790
+ function Promise.prototype:_finalize()
1791
+ for _, callback in ipairs(self._queuedFinally) do
1792
+ -- Purposefully not passing values to callbacks here, as it could be the
1793
+ -- resolved values, or rejected errors. If the developer needs the values,
1794
+ -- they should use :andThen or :catch explicitly.
1795
+ coroutine.wrap(callback)(self._status)
1796
+ end
1797
+
1798
+ self._queuedFinally = nil
1799
+ self._queuedReject = nil
1800
+ self._queuedResolve = nil
1801
+
1802
+ -- Clear references to other Promises to allow gc
1803
+ if not Promise.TEST then
1804
+ self._parent = nil
1805
+ self._consumers = nil
1806
+ end
1807
+
1808
+ task.defer(coroutine.close, self._thread)
1809
+ end
1810
+
1811
+ --[=[
1812
+ Chains a Promise from this one that is resolved if this Promise is already resolved, and rejected if it is not resolved at the time of calling `:now()`. This can be used to ensure your `andThen` handler occurs on the same frame as the root Promise execution.
1813
+
1814
+ ```lua
1815
+ doSomething()
1816
+ :now()
1817
+ :andThen(function(value)
1818
+ print("Got", value, "synchronously.")
1819
+ end)
1820
+ ```
1821
+
1822
+ If this Promise is still running, Rejected, or Cancelled, the Promise returned from `:now()` will reject with the `rejectionValue` if passed, otherwise with a `Promise.Error(Promise.Error.Kind.NotResolvedInTime)`. This can be checked with [[Error.isKind]].
1823
+
1824
+ @param rejectionValue? any -- The value to reject with if the Promise isn't resolved
1825
+ @return Promise
1826
+ ]=]
1827
+ function Promise.prototype:now(rejectionValue)
1828
+ local traceback = debug.traceback(nil, 2)
1829
+ if self._status == Promise.Status.Resolved then
1830
+ return self:_andThen(traceback, function(...)
1831
+ return ...
1832
+ end)
1833
+ else
1834
+ return Promise.reject(rejectionValue == nil and Error.new({
1835
+ kind = Error.Kind.NotResolvedInTime,
1836
+ error = "This Promise was not resolved in time for :now()",
1837
+ context = ":now() was called at:\n\n" .. traceback,
1838
+ }) or rejectionValue)
1839
+ end
1840
+ end
1841
+
1842
+ --[=[
1843
+ Repeatedly calls a Promise-returning function up to `times` number of times, until the returned Promise resolves.
1844
+
1845
+ If the amount of retries is exceeded, the function will return the latest rejected Promise.
1846
+
1847
+ ```lua
1848
+ local function canFail(a, b, c)
1849
+ return Promise.new(function(resolve, reject)
1850
+ -- do something that can fail
1851
+
1852
+ local failed, thing = doSomethingThatCanFail(a, b, c)
1853
+
1854
+ if failed then
1855
+ reject("it failed")
1856
+ else
1857
+ resolve(thing)
1858
+ end
1859
+ end)
1860
+ end
1861
+
1862
+ local MAX_RETRIES = 10
1863
+ local value = Promise.retry(canFail, MAX_RETRIES, "foo", "bar", "baz") -- args to send to canFail
1864
+ ```
1865
+
1866
+ @since 3.0.0
1867
+ @param callback (...: P) -> Promise<T>
1868
+ @param times number
1869
+ @param ...? P
1870
+ @return Promise<T>
1871
+ ]=]
1872
+ function Promise.retry(callback, times, ...)
1873
+ assert(isCallable(callback), "Parameter #1 to Promise.retry must be a function")
1874
+ assert(type(times) == "number", "Parameter #2 to Promise.retry must be a number")
1875
+
1876
+ local args, length = { ... }, select("#", ...)
1877
+
1878
+ return Promise.resolve(callback(...)):catch(function(...)
1879
+ if times > 0 then
1880
+ return Promise.retry(callback, times - 1, unpack(args, 1, length))
1881
+ else
1882
+ return Promise.reject(...)
1883
+ end
1884
+ end)
1885
+ end
1886
+
1887
+ --[=[
1888
+ Repeatedly calls a Promise-returning function up to `times` number of times, waiting `seconds` seconds between each
1889
+ retry, until the returned Promise resolves.
1890
+
1891
+ If the amount of retries is exceeded, the function will return the latest rejected Promise.
1892
+
1893
+ @since v3.2.0
1894
+ @param callback (...: P) -> Promise<T>
1895
+ @param times number
1896
+ @param seconds number
1897
+ @param ...? P
1898
+ @return Promise<T>
1899
+ ]=]
1900
+ function Promise.retryWithDelay(callback, times, seconds, ...)
1901
+ assert(isCallable(callback), "Parameter #1 to Promise.retry must be a function")
1902
+ assert(type(times) == "number", "Parameter #2 (times) to Promise.retry must be a number")
1903
+ assert(type(seconds) == "number", "Parameter #3 (seconds) to Promise.retry must be a number")
1904
+
1905
+ local args, length = { ... }, select("#", ...)
1906
+
1907
+ return Promise.resolve(callback(...)):catch(function(...)
1908
+ if times > 0 then
1909
+ Promise.delay(seconds):await()
1910
+
1911
+ return Promise.retryWithDelay(callback, times - 1, seconds, unpack(args, 1, length))
1912
+ else
1913
+ return Promise.reject(...)
1914
+ end
1915
+ end)
1916
+ end
1917
+
1918
+ --[=[
1919
+ Converts an event into a Promise which resolves the next time the event fires.
1920
+
1921
+ The optional `predicate` callback, if passed, will receive the event arguments and should return `true` or `false`, based on if this fired event should resolve the Promise or not. If `true`, the Promise resolves. If `false`, nothing happens and the predicate will be rerun the next time the event fires.
1922
+
1923
+ The Promise will resolve with the event arguments.
1924
+
1925
+ :::tip
1926
+ This function will work given any object with a `Connect` method. This includes all Roblox events.
1927
+ :::
1928
+
1929
+ ```lua
1930
+ -- Creates a Promise which only resolves when `somePart` is touched
1931
+ -- by a part named `"Something specific"`.
1932
+ return Promise.fromEvent(somePart.Touched, function(part)
1933
+ return part.Name == "Something specific"
1934
+ end)
1935
+ ```
1936
+
1937
+ @since 3.0.0
1938
+ @param event Event -- Any object with a `Connect` method. This includes all Roblox events.
1939
+ @param predicate? (...: P) -> boolean -- A function which determines if the Promise should resolve with the given value, or wait for the next event to check again.
1940
+ @return Promise<P>
1941
+ ]=]
1942
+ function Promise.fromEvent(event, predicate)
1943
+ predicate = predicate or function()
1944
+ return true
1945
+ end
1946
+
1947
+ return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
1948
+ local connection
1949
+ local shouldDisconnect = false
1950
+
1951
+ local function disconnect()
1952
+ connection:Disconnect()
1953
+ connection = nil
1954
+ end
1955
+
1956
+ -- We use shouldDisconnect because if the callback given to Connect is called before
1957
+ -- Connect returns, connection will still be nil. This happens with events that queue up
1958
+ -- events when there's nothing connected, such as RemoteEvents
1959
+
1960
+ connection = event:Connect(function(...)
1961
+ local callbackValue = predicate(...)
1962
+
1963
+ if callbackValue == true then
1964
+ resolve(...)
1965
+
1966
+ if connection then
1967
+ disconnect()
1968
+ else
1969
+ shouldDisconnect = true
1970
+ end
1971
+ elseif type(callbackValue) ~= "boolean" then
1972
+ error("Promise.fromEvent predicate should always return a boolean")
1973
+ end
1974
+ end)
1975
+
1976
+ if shouldDisconnect and connection then
1977
+ return disconnect()
1978
+ end
1979
+
1980
+ onCancel(disconnect)
1981
+ end)
1982
+ end
1983
+
1984
+ --[=[
1985
+ Registers a callback that runs when an unhandled rejection happens. An unhandled rejection happens when a Promise
1986
+ is rejected, and the rejection is not observed with `:catch`.
1987
+
1988
+ The callback is called with the actual promise that rejected, followed by the rejection values.
1989
+
1990
+ @since v3.2.0
1991
+ @param callback (promise: Promise, ...: any) -- A callback that runs when an unhandled rejection happens.
1992
+ @return () -> () -- Function that unregisters the `callback` when called
1993
+ ]=]
1994
+ function Promise.onUnhandledRejection(callback)
1995
+ table.insert(Promise._unhandledRejectionCallbacks, callback)
1996
+
1997
+ return function()
1998
+ local index = table.find(Promise._unhandledRejectionCallbacks, callback)
1999
+
2000
+ if index then
2001
+ table.remove(Promise._unhandledRejectionCallbacks, index)
2002
+ end
2003
+ end
2004
+ end
2005
+
2006
+ return Promise