roblox-opencode 1.0.0 → 1.0.1

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