Advertisement
Guest User

A Roblox Studio error and scripts

a guest
Jul 27th, 2022
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 42.48 KB | None | 0 0
  1. I was testing a script in Roblox Studio and the following errors appeared. I clicked on the errors and it brought me to a few scripts within Roblox Studio that you cannot normally see. The script I was running was not made with the purpose of doing this, something simply went wrong within Roblox Studio, and this happened. I would have put this on the Roblox DevForum, but I can't make posts there due to my rank being nonexistent. It simply didn't give me a rank. Not even visitor. I have no idea if it is against any rules to put source code here, and if it is, there is nothing I can do about it since I'm not going to make an account, meaning that I can't delete this.
  2. error messages printed in output:
  3.  
  4. CorePackages.Packages._Index.roblox_rodux.rodux.thunkMiddleware:15
  5. 14:27:40.327 Unable to get game name for Avatar Editor Prompts - Client - GetGameName:29
  6. 14:27:40.327 Unable to get game name for Gamepad Menu - Client - GetGameName:29
  7. 14:27:40.332 Unhandled Promise rejection:
  8.  
  9. HTTP 500 (Internal Server Error)
  10.  
  11. CoreGui.RobloxGui.CoreScripts/ScreenshotHud:328 function fetchExperienceName
  12. CoreGui.RobloxGui.CoreScripts/ScreenshotHud:661
  13. - Client - Promise:1299
  14. 14:27:40.332 Unhandled Promise rejection:
  15.  
  16. nil
  17.  
  18. CoreGui.RobloxGui.Modules.TopBar.Thunks.GetGameName:23
  19. CorePackages.Packages._Index.roblox_rodux.rodux.thunkMiddleware:15
  20. CorePackages.Packages._Index.roblox_rodux.rodux.thunkMiddleware:14
  21. CorePackages.Packages._Index.roblox_rodux.rodux.Store:98
  22. CoreGui.RobloxGui.Modules.TopBar:88 function new
  23. CoreGui.RobloxGui.Modules.TopBar:139
  24. - Client - Promise:1299
  25. 14:27:40.332 Unhandled Promise rejection:
  26.  
  27. nil
  28.  
  29. CoreGui.RobloxGui.Modules.AvatarEditorPrompts.Thunks.GetGameName:23
  30. CorePackages.Packages._Index.roblox_rodux.rodux.thunkMiddleware:15
  31. CorePackages.Packages._Index.roblox_rodux.rodux.thunkMiddleware:14
  32. CorePackages.Packages._Index.roblox_rodux.rodux.Store:98
  33. CoreGui.RobloxGui.Modules.AvatarEditorPrompts:43 function new
  34. CoreGui.RobloxGui.Modules.AvatarEditorPrompts:81
  35. - Client - Promise:1299
  36.  
  37. script name:
  38. CoreGui.RobloxGui.Modules.AvatarEditorPrompts.Thunks.GetGameName
  39.  
  40. code:
  41. local CoreGui = game:GetService("CoreGui")
  42. local CorePackages = game:GetService("CorePackages")
  43. local HttpRbxApiService = game:GetService("HttpRbxApiService")
  44.  
  45. local RobloxGui = CoreGui:WaitForChild("RobloxGui")
  46.  
  47. local Promise = require(CorePackages.Promise)
  48. local httpRequest = require(CorePackages.AppTempCommon.Temp.httpRequest)
  49.  
  50. local httpImpl = httpRequest(HttpRbxApiService)
  51.  
  52. local Thunks = script.Parent
  53. local AvatarEditorPrompts = Thunks.Parent
  54. local GameNameFetched = require(AvatarEditorPrompts.Actions.GameNameFetched)
  55.  
  56. local GetGameNameAndDescription = require(RobloxGui.Modules.Common.GetGameNameAndDescription)
  57.  
  58. return function(store)
  59. if game.GameId == 0 then
  60. return Promise.resolve()
  61. end
  62.  
  63. return GetGameNameAndDescription(httpImpl, game.GameId):andThen(function(result)
  64. store:dispatch(GameNameFetched(result.Name))
  65.  
  66. return result.Name
  67. end,
  68. function()
  69. warn("Unable to get game name for Avatar Editor Prompts")
  70. return Promise.reject()
  71. end)
  72. end
  73.  
  74. script name:
  75. CoreGui.RobloxGui.Modules.TopBar.Thunks.GetGameName
  76.  
  77. code:
  78. local CoreGui = game:GetService("CoreGui")
  79. local CorePackages = game:GetService("CorePackages")
  80. local HttpRbxApiService = game:GetService("HttpRbxApiService")
  81.  
  82. local RobloxGui = CoreGui:WaitForChild("RobloxGui")
  83.  
  84. local Promise = require(CorePackages.Promise)
  85. local httpRequest = require(CorePackages.AppTempCommon.Temp.httpRequest)
  86.  
  87. local httpImpl = httpRequest(HttpRbxApiService)
  88.  
  89. local Thunks = script.Parent
  90. local TopBar = Thunks.Parent
  91. local SetGameName = require(TopBar.Actions.SetGameName)
  92.  
  93. local GetGameNameAndDescription = require(RobloxGui.Modules.Common.GetGameNameAndDescription)
  94.  
  95. return function(store)
  96. if game.GameId == 0 then
  97. return Promise.resolve()
  98. end
  99.  
  100. return GetGameNameAndDescription(httpImpl, game.GameId):andThen(function(result)
  101. store:dispatch(SetGameName(result.Name))
  102.  
  103. return result.Name
  104. end,
  105. function()
  106. warn("Unable to get game name for Gamepad Menu")
  107. return Promise.reject()
  108. end)
  109. end
  110.  
  111. script name:
  112. CorePackages.Packages._Index.Promise.Promise
  113.  
  114. code:
  115.  
  116. --[[
  117. An implementation of Promises similar to Promise/A+.
  118. ]]
  119.  
  120. local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s"
  121. local ERROR_NON_LIST = "Please pass a list of promises to %s"
  122. local ERROR_NON_FUNCTION = "Please pass a handler function to %s!"
  123. local MODE_KEY_METATABLE = {__mode = "k"}
  124.  
  125. --[[
  126. Creates an enum dictionary with some metamethods to prevent common mistakes.
  127. ]]
  128. local function makeEnum(enumName, members)
  129. local enum = {}
  130.  
  131. for _, memberName in ipairs(members) do
  132. enum[memberName] = memberName
  133. end
  134.  
  135. return setmetatable(enum, {
  136. __index = function(_, k)
  137. error(string.format("%s is not in %s!", k, enumName), 2)
  138. end,
  139. __newindex = function()
  140. error(string.format("Creating new members in %s is not allowed!", enumName), 2)
  141. end,
  142. })
  143. end
  144.  
  145. --[[
  146. An object to represent runtime errors that occur during execution.
  147. Promises that experience an error like this will be rejected with
  148. an instance of this object.
  149. ]]
  150. local Error do
  151. Error = {
  152. Kind = makeEnum("Promise.Error.Kind", {
  153. "ExecutionError",
  154. "AlreadyCancelled",
  155. "NotResolvedInTime",
  156. "TimedOut",
  157. }),
  158. }
  159. Error.__index = Error
  160.  
  161. function Error.new(options, parent)
  162. options = options or {}
  163. return setmetatable({
  164. error = tostring(options.error) or "[This error has no error text.]",
  165. trace = options.trace,
  166. context = options.context,
  167. kind = options.kind,
  168. parent = parent,
  169. createdTick = os.clock(),
  170. createdTrace = debug.traceback(),
  171. }, Error)
  172. end
  173.  
  174. function Error.is(anything)
  175. if type(anything) == "table" then
  176. local metatable = getmetatable(anything)
  177.  
  178. if type(metatable) == "table" then
  179. return rawget(anything, "error") ~= nil and type(rawget(metatable, "extend")) == "function"
  180. end
  181. end
  182.  
  183. return false
  184. end
  185.  
  186. function Error.isKind(anything, kind)
  187. assert(kind ~= nil, "Argument #2 to Promise.Error.isKind must not be nil")
  188.  
  189. return Error.is(anything) and anything.kind == kind
  190. end
  191.  
  192. function Error:extend(options)
  193. options = options or {}
  194.  
  195. options.kind = options.kind or self.kind
  196.  
  197. return Error.new(options, self)
  198. end
  199.  
  200. function Error:getErrorChain()
  201. local runtimeErrors = { self }
  202.  
  203. while runtimeErrors[#runtimeErrors].parent do
  204. table.insert(runtimeErrors, runtimeErrors[#runtimeErrors].parent)
  205. end
  206.  
  207. return runtimeErrors
  208. end
  209.  
  210. function Error:__tostring()
  211. local errorStrings = {
  212. string.format("-- Promise.Error(%s) --", self.kind or "?"),
  213. }
  214.  
  215. for _, runtimeError in ipairs(self:getErrorChain()) do
  216. table.insert(errorStrings, table.concat({
  217. runtimeError.trace or runtimeError.error,
  218. runtimeError.context,
  219. }, "\n"))
  220. end
  221.  
  222. return table.concat(errorStrings, "\n")
  223. end
  224. end
  225.  
  226. --[[
  227. Packs a number of arguments into a table and returns its length.
  228.  
  229. Used to cajole varargs without dropping sparse values.
  230. ]]
  231. local function pack(...)
  232. return select("#", ...), { ... }
  233. end
  234.  
  235. --[[
  236. Returns first value (success), and packs all following values.
  237. ]]
  238. local function packResult(success, ...)
  239. return success, select("#", ...), { ... }
  240. end
  241.  
  242. local function makeErrorHandler(traceback)
  243. assert(traceback ~= nil)
  244.  
  245. return function(err)
  246. -- If the error object is already a table, forward it directly.
  247. -- Should we extend the error here and add our own trace?
  248.  
  249. if type(err) == "table" then
  250. return err
  251. end
  252.  
  253. return Error.new({
  254. error = err,
  255. kind = Error.Kind.ExecutionError,
  256. trace = debug.traceback(tostring(err), 2),
  257. context = "Promise created at:\n\n" .. traceback,
  258. })
  259. end
  260. end
  261.  
  262. --[[
  263. Calls a Promise executor with error handling.
  264. ]]
  265. local function runExecutor(traceback, callback, ...)
  266. return packResult(xpcall(callback, makeErrorHandler(traceback), ...))
  267. end
  268.  
  269. --[[
  270. Creates a function that invokes a callback with correct error handling and
  271. resolution mechanisms.
  272. ]]
  273. local function createAdvancer(traceback, callback, resolve, reject)
  274. return function(...)
  275. local ok, resultLength, result = runExecutor(traceback, callback, ...)
  276.  
  277. if ok then
  278. resolve(unpack(result, 1, resultLength))
  279. else
  280. reject(result[1])
  281. end
  282. end
  283. end
  284.  
  285. local function isEmpty(t)
  286. return next(t) == nil
  287. end
  288.  
  289. local Promise = {
  290. Error = Error,
  291. Status = makeEnum("Promise.Status", {"Started", "Resolved", "Rejected", "Cancelled"}),
  292. _getTime = os.clock,
  293. _timeEvent = game:GetService("RunService").Heartbeat,
  294. _unhandledRejectionCallbacks = {},
  295. }
  296. Promise.prototype = {}
  297. Promise.__index = Promise.prototype
  298.  
  299. --[[
  300. Constructs a new Promise with the given initializing callback.
  301.  
  302. This is generally only called when directly wrapping a non-promise API into
  303. a promise-based version.
  304.  
  305. The callback will receive 'resolve' and 'reject' methods, used to start
  306. invoking the promise chain.
  307.  
  308. Second parameter, parent, is used internally for tracking the "parent" in a
  309. promise chain. External code shouldn't need to worry about this.
  310. ]]
  311. function Promise._new(traceback, callback, parent)
  312. if parent ~= nil and not Promise.is(parent) then
  313. error("Argument #2 to Promise.new must be a promise or nil", 2)
  314. end
  315.  
  316. local self = {
  317. -- Used to locate where a promise was created
  318. _source = traceback,
  319.  
  320. _status = Promise.Status.Started,
  321.  
  322. -- A table containing a list of all results, whether success or failure.
  323. -- Only valid if _status is set to something besides Started
  324. _values = nil,
  325.  
  326. -- Lua doesn't like sparse arrays very much, so we explicitly store the
  327. -- length of _values to handle middle nils.
  328. _valuesLength = -1,
  329.  
  330. -- Tracks if this Promise has no error observers..
  331. _unhandledRejection = true,
  332.  
  333. -- Queues representing functions we should invoke when we update!
  334. _queuedResolve = {},
  335. _queuedReject = {},
  336. _queuedFinally = {},
  337.  
  338. -- The function to run when/if this promise is cancelled.
  339. _cancellationHook = nil,
  340.  
  341. -- The "parent" of this promise in a promise chain. Required for
  342. -- cancellation propagation upstream.
  343. _parent = parent,
  344.  
  345. -- Consumers are Promises that have chained onto this one.
  346. -- We track them for cancellation propagation downstream.
  347. _consumers = setmetatable({}, MODE_KEY_METATABLE),
  348. }
  349.  
  350. if parent and parent._status == Promise.Status.Started then
  351. parent._consumers[self] = true
  352. end
  353.  
  354. setmetatable(self, Promise)
  355.  
  356. local function resolve(...)
  357. self:_resolve(...)
  358. end
  359.  
  360. local function reject(...)
  361. self:_reject(...)
  362. end
  363.  
  364. local function onCancel(cancellationHook)
  365. if cancellationHook then
  366. if self._status == Promise.Status.Cancelled then
  367. cancellationHook()
  368. else
  369. self._cancellationHook = cancellationHook
  370. end
  371. end
  372.  
  373. return self._status == Promise.Status.Cancelled
  374. end
  375.  
  376. coroutine.wrap(function()
  377. local ok, _, result = runExecutor(
  378. self._source,
  379. callback,
  380. resolve,
  381. reject,
  382. onCancel
  383. )
  384.  
  385. if not ok then
  386. reject(result[1])
  387. end
  388. end)()
  389.  
  390. return self
  391. end
  392.  
  393. function Promise.new(executor)
  394. return Promise._new(debug.traceback(nil, 2), executor)
  395. end
  396.  
  397. function Promise:__tostring()
  398. return string.format("Promise(%s)", self._status)
  399. end
  400.  
  401. --[[
  402. Promise.new, except pcall on a new thread is automatic.
  403. ]]
  404. function Promise.defer(callback)
  405. local traceback = debug.traceback(nil, 2)
  406. local promise
  407. promise = Promise._new(traceback, function(resolve, reject, onCancel)
  408. local connection
  409. connection = Promise._timeEvent:Connect(function()
  410. connection:Disconnect()
  411. local ok, _, result = runExecutor(traceback, callback, resolve, reject, onCancel)
  412.  
  413. if not ok then
  414. reject(result[1])
  415. end
  416. end)
  417. end)
  418.  
  419. return promise
  420. end
  421.  
  422. -- Backwards compatibility
  423. Promise.async = Promise.defer
  424.  
  425. --[[
  426. Create a promise that represents the immediately resolved value.
  427. ]]
  428. function Promise.resolve(...)
  429. local length, values = pack(...)
  430. return Promise._new(debug.traceback(nil, 2), function(resolve)
  431. resolve(unpack(values, 1, length))
  432. end)
  433. end
  434.  
  435. --[[
  436. Create a promise that represents the immediately rejected value.
  437. ]]
  438. function Promise.reject(...)
  439. local length, values = pack(...)
  440. return Promise._new(debug.traceback(nil, 2), function(_, reject)
  441. reject(unpack(values, 1, length))
  442. end)
  443. end
  444.  
  445. --[[
  446. Runs a non-promise-returning function as a Promise with the
  447. given arguments.
  448. ]]
  449. function Promise._try(traceback, callback, ...)
  450. local valuesLength, values = pack(...)
  451.  
  452. return Promise._new(traceback, function(resolve)
  453. resolve(callback(unpack(values, 1, valuesLength)))
  454. end)
  455. end
  456.  
  457. --[[
  458. Begins a Promise chain, turning synchronous errors into rejections.
  459. ]]
  460. function Promise.try(...)
  461. return Promise._try(debug.traceback(nil, 2), ...)
  462. end
  463.  
  464. --[[
  465. Returns a new promise that:
  466. * is resolved when all input promises resolve
  467. * is rejected if ANY input promises reject
  468. ]]
  469. function Promise._all(traceback, promises, amount)
  470. if type(promises) ~= "table" then
  471. error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
  472. end
  473.  
  474. -- We need to check that each value is a promise here so that we can produce
  475. -- a proper error rather than a rejected promise with our error.
  476. for i, promise in pairs(promises) do
  477. if not Promise.is(promise) then
  478. error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
  479. end
  480. end
  481.  
  482. -- If there are no values then return an already resolved promise.
  483. if #promises == 0 or amount == 0 then
  484. return Promise.resolve({})
  485. end
  486.  
  487. return Promise._new(traceback, function(resolve, reject, onCancel)
  488. -- An array to contain our resolved values from the given promises.
  489. local resolvedValues = {}
  490. local newPromises = {}
  491.  
  492. -- Keep a count of resolved promises because just checking the resolved
  493. -- values length wouldn't account for promises that resolve with nil.
  494. local resolvedCount = 0
  495. local rejectedCount = 0
  496. local done = false
  497.  
  498. local function cancel()
  499. for _, promise in ipairs(newPromises) do
  500. promise:cancel()
  501. end
  502. end
  503.  
  504. -- Called when a single value is resolved and resolves if all are done.
  505. local function resolveOne(i, ...)
  506. if done then
  507. return
  508. end
  509.  
  510. resolvedCount = resolvedCount + 1
  511.  
  512. if amount == nil then
  513. resolvedValues[i] = ...
  514. else
  515. resolvedValues[resolvedCount] = ...
  516. end
  517.  
  518. if resolvedCount >= (amount or #promises) then
  519. done = true
  520. resolve(resolvedValues)
  521. cancel()
  522. end
  523. end
  524.  
  525. onCancel(cancel)
  526.  
  527. -- We can assume the values inside `promises` are all promises since we
  528. -- checked above.
  529. for i, promise in ipairs(promises) do
  530. newPromises[i] = promise:andThen(
  531. function(...)
  532. resolveOne(i, ...)
  533. end,
  534. function(...)
  535. rejectedCount = rejectedCount + 1
  536.  
  537. if amount == nil or #promises - rejectedCount < amount then
  538. cancel()
  539. done = true
  540.  
  541. reject(...)
  542. end
  543. end
  544. )
  545. end
  546.  
  547. if done then
  548. cancel()
  549. end
  550. end)
  551. end
  552.  
  553. function Promise.all(...)
  554. local promises = {...}
  555.  
  556. -- check if we've been given a list of promises, not just a variable number of promises
  557. if type(promises[1]) == "table" and not Promise.is(promises[1]) then
  558. -- we've been given a table of promises already
  559. promises = promises[1]
  560. end
  561.  
  562. return Promise._all(debug.traceback(nil, 2), promises)
  563. end
  564.  
  565. function Promise.fold(list, callback, initialValue)
  566. assert(type(list) == "table", "Bad argument #1 to Promise.fold: must be a table")
  567. assert(type(callback) == "function", "Bad argument #2 to Promise.fold: must be a function")
  568.  
  569. local accumulator = Promise.resolve(initialValue)
  570. return Promise.each(list, function(resolvedElement, i)
  571. accumulator = accumulator:andThen(function(previousValueResolved)
  572. return callback(previousValueResolved, resolvedElement, i)
  573. end)
  574. end):andThenReturn(accumulator)
  575. end
  576.  
  577. function Promise.some(promises, amount)
  578. assert(type(amount) == "number", "Bad argument #2 to Promise.some: must be a number")
  579.  
  580. return Promise._all(debug.traceback(nil, 2), promises, amount)
  581. end
  582.  
  583. function Promise.any(promises)
  584. return Promise._all(debug.traceback(nil, 2), promises, 1):andThen(function(values)
  585. return values[1]
  586. end)
  587. end
  588.  
  589. function Promise.allSettled(promises)
  590. if type(promises) ~= "table" then
  591. error(string.format(ERROR_NON_LIST, "Promise.allSettled"), 2)
  592. end
  593.  
  594. -- We need to check that each value is a promise here so that we can produce
  595. -- a proper error rather than a rejected promise with our error.
  596. for i, promise in pairs(promises) do
  597. if not Promise.is(promise) then
  598. error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.allSettled", tostring(i)), 2)
  599. end
  600. end
  601.  
  602. -- If there are no values then return an already resolved promise.
  603. if #promises == 0 then
  604. return Promise.resolve({})
  605. end
  606.  
  607. return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
  608. -- An array to contain our resolved values from the given promises.
  609. local fates = {}
  610. local newPromises = {}
  611.  
  612. -- Keep a count of resolved promises because just checking the resolved
  613. -- values length wouldn't account for promises that resolve with nil.
  614. local finishedCount = 0
  615.  
  616. -- Called when a single value is resolved and resolves if all are done.
  617. local function resolveOne(i, ...)
  618. finishedCount = finishedCount + 1
  619.  
  620. fates[i] = ...
  621.  
  622. if finishedCount >= #promises then
  623. resolve(fates)
  624. end
  625. end
  626.  
  627. onCancel(function()
  628. for _, promise in ipairs(newPromises) do
  629. promise:cancel()
  630. end
  631. end)
  632.  
  633. -- We can assume the values inside `promises` are all promises since we
  634. -- checked above.
  635. for i, promise in ipairs(promises) do
  636. newPromises[i] = promise:finally(
  637. function(...)
  638. resolveOne(i, ...)
  639. end
  640. )
  641. end
  642. end)
  643. end
  644.  
  645. --[[
  646. Races a set of Promises and returns the first one that resolves,
  647. cancelling the others.
  648. ]]
  649. function Promise.race(promises)
  650. assert(type(promises) == "table", string.format(ERROR_NON_LIST, "Promise.race"))
  651.  
  652. for i, promise in pairs(promises) do
  653. assert(Promise.is(promise), string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.race", tostring(i)))
  654. end
  655.  
  656. return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
  657. local newPromises = {}
  658. local finished = false
  659.  
  660. local function cancel()
  661. for _, promise in ipairs(newPromises) do
  662. promise:cancel()
  663. end
  664. end
  665.  
  666. local function finalize(callback)
  667. return function (...)
  668. cancel()
  669. finished = true
  670. return callback(...)
  671. end
  672. end
  673.  
  674. if onCancel(finalize(reject)) then
  675. return
  676. end
  677.  
  678. for i, promise in ipairs(promises) do
  679. newPromises[i] = promise:andThen(finalize(resolve), finalize(reject))
  680. end
  681.  
  682. if finished then
  683. cancel()
  684. end
  685. end)
  686. end
  687.  
  688. --[[
  689. Iterates serially over the given an array of values, calling the predicate callback on each before continuing.
  690. If the predicate returns a Promise, we wait for that Promise to resolve before continuing to the next item
  691. in the array. If the Promise the predicate returns rejects, the Promise from Promise.each is also rejected with
  692. the same value.
  693.  
  694. Returns a Promise containing an array of the return values from the predicate for each item in the original list.
  695. ]]
  696. function Promise.each(list, predicate)
  697. assert(type(list) == "table", string.format(ERROR_NON_LIST, "Promise.each"))
  698. assert(type(predicate) == "function", string.format(ERROR_NON_FUNCTION, "Promise.each"))
  699.  
  700. return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
  701. local results = {}
  702. local promisesToCancel = {}
  703.  
  704. local cancelled = false
  705.  
  706. local function cancel()
  707. for _, promiseToCancel in ipairs(promisesToCancel) do
  708. promiseToCancel:cancel()
  709. end
  710. end
  711.  
  712. onCancel(function()
  713. cancelled = true
  714.  
  715. cancel()
  716. end)
  717.  
  718. -- We need to preprocess the list of values and look for Promises.
  719. -- If we find some, we must register our andThen calls now, so that those Promises have a consumer
  720. -- from us registered. If we don't do this, those Promises might get cancelled by something else
  721. -- before we get to them in the series because it's not possible to tell that we plan to use it
  722. -- unless we indicate it here.
  723.  
  724. local preprocessedList = {}
  725.  
  726. for index, value in ipairs(list) do
  727. if Promise.is(value) then
  728. if value:getStatus() == Promise.Status.Cancelled then
  729. cancel()
  730. return reject(Error.new({
  731. error = "Promise is cancelled",
  732. kind = Error.Kind.AlreadyCancelled,
  733. context = string.format(
  734. "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",
  735. index,
  736. value._source
  737. ),
  738. }))
  739. elseif value:getStatus() == Promise.Status.Rejected then
  740. cancel()
  741. return reject(select(2, value:await()))
  742. end
  743.  
  744. -- Chain a new Promise from this one so we only cancel ours
  745. local ourPromise = value:andThen(function(...)
  746. return ...
  747. end)
  748.  
  749. table.insert(promisesToCancel, ourPromise)
  750. preprocessedList[index] = ourPromise
  751. else
  752. preprocessedList[index] = value
  753. end
  754. end
  755.  
  756. for index, value in ipairs(preprocessedList) do
  757. if Promise.is(value) then
  758. local success
  759. success, value = value:await()
  760.  
  761. if not success then
  762. cancel()
  763. return reject(value)
  764. end
  765. end
  766.  
  767. if cancelled then
  768. return
  769. end
  770.  
  771. local predicatePromise = Promise.resolve(predicate(value, index))
  772.  
  773. table.insert(promisesToCancel, predicatePromise)
  774.  
  775. local success, result = predicatePromise:await()
  776.  
  777. if not success then
  778. cancel()
  779. return reject(result)
  780. end
  781.  
  782. results[index] = result
  783. end
  784.  
  785. resolve(results)
  786. end)
  787. end
  788.  
  789. --[[
  790. Is the given object a Promise instance?
  791. ]]
  792. function Promise.is(object)
  793. if type(object) ~= "table" then
  794. return false
  795. end
  796.  
  797. local objectMetatable = getmetatable(object)
  798.  
  799. if objectMetatable == Promise then
  800. -- The Promise came from this library.
  801. return true
  802. elseif objectMetatable == nil then
  803. -- No metatable, but we should still chain onto tables with andThen methods
  804. return type(object.andThen) == "function"
  805. elseif
  806. type(objectMetatable) == "table"
  807. and type(rawget(objectMetatable, "__index")) == "table"
  808. and type(rawget(rawget(objectMetatable, "__index"), "andThen")) == "function"
  809. then
  810. -- Maybe this came from a different or older Promise library.
  811. return true
  812. end
  813.  
  814. return false
  815. end
  816.  
  817. --[[
  818. Converts a yielding function into a Promise-returning one.
  819. ]]
  820. function Promise.promisify(callback)
  821. return function(...)
  822. return Promise._try(debug.traceback(nil, 2), callback, ...)
  823. end
  824. end
  825.  
  826. --[[
  827. Creates a Promise that resolves after given number of seconds.
  828. ]]
  829. do
  830. -- uses a sorted doubly linked list (queue) to achieve O(1) remove operations and O(n) for insert
  831.  
  832. -- the initial node in the linked list
  833. local first
  834. local connection
  835.  
  836. function Promise.delay(seconds)
  837. assert(type(seconds) == "number", "Bad argument #1 to Promise.delay, must be a number.")
  838. -- If seconds is -INF, INF, NaN, or less than 1 / 60, assume seconds is 1 / 60.
  839. -- This mirrors the behavior of wait()
  840. if not (seconds >= 1 / 60) or seconds == math.huge then
  841. seconds = 1 / 60
  842. end
  843.  
  844. return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
  845. local startTime = Promise._getTime()
  846. local endTime = startTime + seconds
  847.  
  848. local node = {
  849. resolve = resolve,
  850. startTime = startTime,
  851. endTime = endTime,
  852. }
  853.  
  854. if connection == nil then -- first is nil when connection is nil
  855. first = node
  856. connection = Promise._timeEvent:Connect(function()
  857. local threadStart = Promise._getTime()
  858.  
  859. while first ~= nil and first.endTime < threadStart do
  860. local current = first
  861. first = current.next
  862.  
  863. if first == nil then
  864. connection:Disconnect()
  865. connection = nil
  866. else
  867. first.previous = nil
  868. end
  869.  
  870. current.resolve(Promise._getTime() - current.startTime)
  871. end
  872. end)
  873. else -- first is non-nil
  874. if first.endTime < endTime then -- if `node` should be placed after `first`
  875. -- we will insert `node` between `current` and `next`
  876. -- (i.e. after `current` if `next` is nil)
  877. local current = first
  878. local next = current.next
  879.  
  880. while next ~= nil and next.endTime < endTime do
  881. current = next
  882. next = current.next
  883. end
  884.  
  885. -- `current` must be non-nil, but `next` could be `nil` (i.e. last item in list)
  886. current.next = node
  887. node.previous = current
  888.  
  889. if next ~= nil then
  890. node.next = next
  891. next.previous = node
  892. end
  893. else
  894. -- set `node` to `first`
  895. node.next = first
  896. first.previous = node
  897. first = node
  898. end
  899. end
  900.  
  901. onCancel(function()
  902. -- remove node from queue
  903. local next = node.next
  904.  
  905. if first == node then
  906. if next == nil then -- if `node` is the first and last
  907. connection:Disconnect()
  908. connection = nil
  909. else -- if `node` is `first` and not the last
  910. next.previous = nil
  911. end
  912. first = next
  913. else
  914. local previous = node.previous
  915. -- since `node` is not `first`, then we know `previous` is non-nil
  916. previous.next = next
  917.  
  918. if next ~= nil then
  919. next.previous = previous
  920. end
  921. end
  922. end)
  923. end)
  924. end
  925. end
  926.  
  927. --[[
  928. Rejects the promise after `seconds` seconds.
  929. ]]
  930. function Promise.prototype:timeout(seconds, rejectionValue)
  931. local traceback = debug.traceback(nil, 2)
  932.  
  933. return Promise.race({
  934. Promise.delay(seconds):andThen(function()
  935. return Promise.reject(rejectionValue == nil and Error.new({
  936. kind = Error.Kind.TimedOut,
  937. error = "Timed out",
  938. context = string.format(
  939. "Timeout of %d seconds exceeded.\n:timeout() called at:\n\n%s",
  940. seconds,
  941. traceback
  942. ),
  943. }) or rejectionValue)
  944. end),
  945. self,
  946. })
  947. end
  948.  
  949. function Promise.prototype:getStatus()
  950. return self._status
  951. end
  952.  
  953. --[[
  954. Creates a new promise that receives the result of this promise.
  955.  
  956. The given callbacks are invoked depending on that result.
  957. ]]
  958. function Promise.prototype:_andThen(traceback, successHandler, failureHandler)
  959. self._unhandledRejection = false
  960.  
  961. -- Create a new promise to follow this part of the chain
  962. return Promise._new(traceback, function(resolve, reject)
  963. -- Our default callbacks just pass values onto the next promise.
  964. -- This lets success and failure cascade correctly!
  965.  
  966. local successCallback = resolve
  967. if successHandler then
  968. successCallback = createAdvancer(
  969. traceback,
  970. successHandler,
  971. resolve,
  972. reject
  973. )
  974. end
  975.  
  976. local failureCallback = reject
  977. if failureHandler then
  978. failureCallback = createAdvancer(
  979. traceback,
  980. failureHandler,
  981. resolve,
  982. reject
  983. )
  984. end
  985.  
  986. if self._status == Promise.Status.Started then
  987. -- If we haven't resolved yet, put ourselves into the queue
  988. table.insert(self._queuedResolve, successCallback)
  989. table.insert(self._queuedReject, failureCallback)
  990. elseif self._status == Promise.Status.Resolved then
  991. -- This promise has already resolved! Trigger success immediately.
  992. successCallback(unpack(self._values, 1, self._valuesLength))
  993. elseif self._status == Promise.Status.Rejected then
  994. -- This promise died a terrible death! Trigger failure immediately.
  995. failureCallback(unpack(self._values, 1, self._valuesLength))
  996. elseif self._status == Promise.Status.Cancelled then
  997. -- We don't want to call the success handler or the failure handler,
  998. -- we just reject this promise outright.
  999. reject(Error.new({
  1000. error = "Promise is cancelled",
  1001. kind = Error.Kind.AlreadyCancelled,
  1002. context = "Promise created at\n\n" .. traceback,
  1003. }))
  1004. end
  1005. end, self)
  1006. end
  1007.  
  1008. function Promise.prototype:andThen(successHandler, failureHandler)
  1009. assert(
  1010. successHandler == nil or type(successHandler) == "function" or successHandler.__call ~= nil,
  1011. string.format(ERROR_NON_FUNCTION, "Promise:andThen")
  1012. )
  1013. assert(
  1014. failureHandler == nil or type(failureHandler) == "function" or failureHandler.__call ~= nil,
  1015. string.format(ERROR_NON_FUNCTION, "Promise:andThen")
  1016. )
  1017.  
  1018. return self:_andThen(debug.traceback(nil, 2), successHandler, failureHandler)
  1019. end
  1020.  
  1021. --[[
  1022. Used to catch any errors that may have occurred in the promise.
  1023. ]]
  1024. function Promise.prototype:catch(failureCallback)
  1025. assert(
  1026. failureCallback == nil or type(failureCallback) == "function" or failureCallback.__call ~= nil,
  1027. string.format(ERROR_NON_FUNCTION, "Promise:catch")
  1028. )
  1029. return self:_andThen(debug.traceback(nil, 2), nil, failureCallback)
  1030. end
  1031.  
  1032. --[[
  1033. Like andThen, but the value passed into the handler is also the
  1034. value returned from the handler.
  1035. ]]
  1036. function Promise.prototype:tap(tapCallback)
  1037. assert(type(tapCallback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:tap"))
  1038. return self:_andThen(debug.traceback(nil, 2), function(...)
  1039. local callbackReturn = tapCallback(...)
  1040.  
  1041. if Promise.is(callbackReturn) then
  1042. local length, values = pack(...)
  1043. return callbackReturn:andThen(function()
  1044. return unpack(values, 1, length)
  1045. end)
  1046. end
  1047.  
  1048. return ...
  1049. end)
  1050. end
  1051.  
  1052. --[[
  1053. Calls a callback on `andThen` with specific arguments.
  1054. ]]
  1055. function Promise.prototype:andThenCall(callback, ...)
  1056. assert(type(callback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:andThenCall"))
  1057. local length, values = pack(...)
  1058. return self:_andThen(debug.traceback(nil, 2), function()
  1059. return callback(unpack(values, 1, length))
  1060. end)
  1061. end
  1062.  
  1063. --[[
  1064. Shorthand for an andThen handler that returns the given value.
  1065. ]]
  1066. function Promise.prototype:andThenReturn(...)
  1067. local length, values = pack(...)
  1068. return self:_andThen(debug.traceback(nil, 2), function()
  1069. return unpack(values, 1, length)
  1070. end)
  1071. end
  1072.  
  1073. --[[
  1074. Cancels the promise, disallowing it from rejecting or resolving, and calls
  1075. the cancellation hook if provided.
  1076. ]]
  1077. function Promise.prototype:cancel()
  1078. if self._status ~= Promise.Status.Started then
  1079. return
  1080. end
  1081.  
  1082. self._status = Promise.Status.Cancelled
  1083.  
  1084. if self._cancellationHook then
  1085. self._cancellationHook()
  1086. end
  1087.  
  1088. if self._parent then
  1089. self._parent:_consumerCancelled(self)
  1090. end
  1091.  
  1092. for child in pairs(self._consumers) do
  1093. child:cancel()
  1094. end
  1095.  
  1096. self:_finalize()
  1097. end
  1098.  
  1099. --[[
  1100. Used to decrease the number of consumers by 1, and if there are no more,
  1101. cancel this promise.
  1102. ]]
  1103. function Promise.prototype:_consumerCancelled(consumer)
  1104. if self._status ~= Promise.Status.Started then
  1105. return
  1106. end
  1107.  
  1108. self._consumers[consumer] = nil
  1109.  
  1110. if next(self._consumers) == nil then
  1111. self:cancel()
  1112. end
  1113. end
  1114.  
  1115. --[[
  1116. Used to set a handler for when the promise resolves, rejects, or is
  1117. cancelled. Returns a new promise chained from this promise.
  1118. ]]
  1119. function Promise.prototype:_finally(traceback, finallyHandler, onlyOk)
  1120. if not onlyOk then
  1121. self._unhandledRejection = false
  1122. end
  1123.  
  1124. -- Return a promise chained off of this promise
  1125. return Promise._new(traceback, function(resolve, reject)
  1126. local finallyCallback = resolve
  1127. if finallyHandler then
  1128. finallyCallback = createAdvancer(
  1129. traceback,
  1130. finallyHandler,
  1131. resolve,
  1132. reject
  1133. )
  1134. end
  1135.  
  1136. if onlyOk then
  1137. local callback = finallyCallback
  1138. finallyCallback = function(...)
  1139. if self._status == Promise.Status.Rejected then
  1140. return resolve(self)
  1141. end
  1142.  
  1143. return callback(...)
  1144. end
  1145. end
  1146.  
  1147. if self._status == Promise.Status.Started then
  1148. -- The promise is not settled, so queue this.
  1149. table.insert(self._queuedFinally, finallyCallback)
  1150. else
  1151. -- The promise already settled or was cancelled, run the callback now.
  1152. finallyCallback(self._status)
  1153. end
  1154. end, self)
  1155. end
  1156.  
  1157. function Promise.prototype:finally(finallyHandler)
  1158. assert(
  1159. finallyHandler == nil or type(finallyHandler) == "function" or finallyHandler.__call ~= nill,
  1160. string.format(ERROR_NON_FUNCTION, "Promise:finally")
  1161. )
  1162. return self:_finally(debug.traceback(nil, 2), finallyHandler)
  1163. end
  1164.  
  1165. --[[
  1166. Calls a callback on `finally` with specific arguments.
  1167. ]]
  1168. function Promise.prototype:finallyCall(callback, ...)
  1169. assert(type(callback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:finallyCall"))
  1170. local length, values = pack(...)
  1171. return self:_finally(debug.traceback(nil, 2), function()
  1172. return callback(unpack(values, 1, length))
  1173. end)
  1174. end
  1175.  
  1176. --[[
  1177. Shorthand for a finally handler that returns the given value.
  1178. ]]
  1179. function Promise.prototype:finallyReturn(...)
  1180. local length, values = pack(...)
  1181. return self:_finally(debug.traceback(nil, 2), function()
  1182. return unpack(values, 1, length)
  1183. end)
  1184. end
  1185.  
  1186. --[[
  1187. Similar to finally, except rejections are propagated through it.
  1188. ]]
  1189. function Promise.prototype:done(finallyHandler)
  1190. assert(
  1191. finallyHandler == nil or type(finallyHandler) == "function" or finallyHandler.__call ~= nill,
  1192. string.format(ERROR_NON_FUNCTION, "Promise:done")
  1193. )
  1194. return self:_finally(debug.traceback(nil, 2), finallyHandler, true)
  1195. end
  1196.  
  1197. --[[
  1198. Calls a callback on `done` with specific arguments.
  1199. ]]
  1200. function Promise.prototype:doneCall(callback, ...)
  1201. assert(type(callback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:doneCall"))
  1202. local length, values = pack(...)
  1203. return self:_finally(debug.traceback(nil, 2), function()
  1204. return callback(unpack(values, 1, length))
  1205. end, true)
  1206. end
  1207.  
  1208. --[[
  1209. Shorthand for a done handler that returns the given value.
  1210. ]]
  1211. function Promise.prototype:doneReturn(...)
  1212. local length, values = pack(...)
  1213. return self:_finally(debug.traceback(nil, 2), function()
  1214. return unpack(values, 1, length)
  1215. end, true)
  1216. end
  1217.  
  1218. --[[
  1219. Yield until the promise is completed.
  1220.  
  1221. This matches the execution model of normal Roblox functions.
  1222. ]]
  1223. function Promise.prototype:awaitStatus()
  1224. self._unhandledRejection = false
  1225.  
  1226. if self._status == Promise.Status.Started then
  1227. local bindable = Instance.new("BindableEvent")
  1228.  
  1229. self:finally(function()
  1230. bindable:Fire()
  1231. end)
  1232.  
  1233. bindable.Event:Wait()
  1234. bindable:Destroy()
  1235. end
  1236.  
  1237. if self._status == Promise.Status.Resolved then
  1238. return self._status, unpack(self._values, 1, self._valuesLength)
  1239. elseif self._status == Promise.Status.Rejected then
  1240. return self._status, unpack(self._values, 1, self._valuesLength)
  1241. end
  1242.  
  1243. return self._status
  1244. end
  1245.  
  1246. local function awaitHelper(status, ...)
  1247. return status == Promise.Status.Resolved, ...
  1248. end
  1249.  
  1250. --[[
  1251. Calls awaitStatus internally, returns (isResolved, values...)
  1252. ]]
  1253. function Promise.prototype:await()
  1254. return awaitHelper(self:awaitStatus())
  1255. end
  1256.  
  1257. local function expectHelper(status, ...)
  1258. if status ~= Promise.Status.Resolved then
  1259. error((...) == nil and "Expected Promise rejected with no value." or (...), 3)
  1260. end
  1261.  
  1262. return ...
  1263. end
  1264.  
  1265. --[[
  1266. Calls await and only returns if the Promise resolves.
  1267. Throws if the Promise rejects or gets cancelled.
  1268. ]]
  1269. function Promise.prototype:expect()
  1270. return expectHelper(self:awaitStatus())
  1271. end
  1272.  
  1273. -- Backwards compatibility
  1274. Promise.prototype.awaitValue = Promise.prototype.expect
  1275.  
  1276. --[[
  1277. Intended for use in tests.
  1278.  
  1279. Similar to await(), but instead of yielding if the promise is unresolved,
  1280. _unwrap will throw. This indicates an assumption that a promise has
  1281. resolved.
  1282. ]]
  1283. function Promise.prototype:_unwrap()
  1284. if self._status == Promise.Status.Started then
  1285. error("Promise has not resolved or rejected.", 2)
  1286. end
  1287.  
  1288. local success = self._status == Promise.Status.Resolved
  1289.  
  1290. return success, unpack(self._values, 1, self._valuesLength)
  1291. end
  1292.  
  1293. function Promise.prototype:_resolve(...)
  1294. if self._status ~= Promise.Status.Started then
  1295. if Promise.is((...)) then
  1296. (...):_consumerCancelled(self)
  1297. end
  1298. return
  1299. end
  1300.  
  1301. -- If the resolved value was a Promise, we chain onto it!
  1302. if Promise.is((...)) then
  1303. -- Without this warning, arguments sometimes mysteriously disappear
  1304. if select("#", ...) > 1 then
  1305. local message = string.format(
  1306. "When returning a Promise from andThen, extra arguments are " ..
  1307. "discarded! See:\n\n%s",
  1308. self._source
  1309. )
  1310. warn(message)
  1311. end
  1312.  
  1313. local chainedPromise = ...
  1314.  
  1315. local promise = chainedPromise:andThen(
  1316. function(...)
  1317. self:_resolve(...)
  1318. end,
  1319. function(...)
  1320. local maybeRuntimeError = chainedPromise._values[1]
  1321.  
  1322. -- Backwards compatibility < v2
  1323. if chainedPromise._error then
  1324. maybeRuntimeError = Error.new({
  1325. error = chainedPromise._error,
  1326. kind = Error.Kind.ExecutionError,
  1327. context = "[No stack trace available as this Promise originated from an older version of the Promise library (< v2)]",
  1328. })
  1329. end
  1330.  
  1331. if Error.isKind(maybeRuntimeError, Error.Kind.ExecutionError) then
  1332. return self:_reject(maybeRuntimeError:extend({
  1333. error = "This Promise was chained to a Promise that errored.",
  1334. trace = "",
  1335. context = string.format(
  1336. "The Promise at:\n\n%s\n...Rejected because it was chained to the following Promise, which encountered an error:\n",
  1337. self._source
  1338. ),
  1339. }))
  1340. end
  1341.  
  1342. self:_reject(...)
  1343. end
  1344. )
  1345.  
  1346. if promise._status == Promise.Status.Cancelled then
  1347. self:cancel()
  1348. elseif promise._status == Promise.Status.Started then
  1349. -- Adopt ourselves into promise for cancellation propagation.
  1350. self._parent = promise
  1351. promise._consumers[self] = true
  1352. end
  1353.  
  1354. return
  1355. end
  1356.  
  1357. self._status = Promise.Status.Resolved
  1358. self._valuesLength, self._values = pack(...)
  1359.  
  1360. -- We assume that these callbacks will not throw errors.
  1361. for _, callback in ipairs(self._queuedResolve) do
  1362. coroutine.wrap(callback)(...)
  1363. end
  1364.  
  1365. self:_finalize()
  1366. end
  1367.  
  1368. function Promise.prototype:_reject(...)
  1369. if self._status ~= Promise.Status.Started then
  1370. return
  1371. end
  1372.  
  1373. self._status = Promise.Status.Rejected
  1374. self._valuesLength, self._values = pack(...)
  1375.  
  1376. -- If there are any rejection handlers, call those!
  1377. if not isEmpty(self._queuedReject) then
  1378. -- We assume that these callbacks will not throw errors.
  1379. for _, callback in ipairs(self._queuedReject) do
  1380. coroutine.wrap(callback)(...)
  1381. end
  1382. else
  1383. -- At this point, no one was able to observe the error.
  1384. -- An error handler might still be attached if the error occurred
  1385. -- synchronously. We'll wait one tick, and if there are still no
  1386. -- observers, then we should put a message in the console.
  1387.  
  1388. local err = tostring((...))
  1389.  
  1390. coroutine.wrap(function()
  1391. Promise._timeEvent:Wait()
  1392.  
  1393. -- Someone observed the error, hooray!
  1394. if not self._unhandledRejection then
  1395. return
  1396. end
  1397.  
  1398. -- Build a reasonable message
  1399. local message = string.format(
  1400. "Unhandled Promise rejection:\n\n%s\n\n%s",
  1401. err,
  1402. self._source
  1403. )
  1404.  
  1405. for _, callback in ipairs(Promise._unhandledRejectionCallbacks) do
  1406. task.spawn(callback, self, unpack(self._values, 1, self._valuesLength))
  1407. end
  1408.  
  1409. if Promise.TEST then
  1410. -- Don't spam output when we're running tests.
  1411. return
  1412. end
  1413.  
  1414. warn(message)
  1415. end)()
  1416. end
  1417.  
  1418. self:_finalize()
  1419. end
  1420.  
  1421. --[[
  1422. Calls any :finally handlers. We need this to be a separate method and
  1423. queue because we must call all of the finally callbacks upon a success,
  1424. failure, *and* cancellation.
  1425. ]]
  1426. function Promise.prototype:_finalize()
  1427. for _, callback in ipairs(self._queuedFinally) do
  1428. -- Purposefully not passing values to callbacks here, as it could be the
  1429. -- resolved values, or rejected errors. If the developer needs the values,
  1430. -- they should use :andThen or :catch explicitly.
  1431. coroutine.wrap(callback)(self._status)
  1432. end
  1433.  
  1434. self._queuedFinally = nil
  1435. self._queuedReject = nil
  1436. self._queuedResolve = nil
  1437.  
  1438. -- Clear references to other Promises to allow gc
  1439. if not Promise.TEST then
  1440. self._parent = nil
  1441. self._consumers = nil
  1442. end
  1443. end
  1444.  
  1445. --[[
  1446. Chains a Promise from this one that is resolved if this Promise is
  1447. resolved, and rejected if it is not resolved.
  1448. ]]
  1449. function Promise.prototype:now(rejectionValue)
  1450. local traceback = debug.traceback(nil, 2)
  1451. if self._status == Promise.Status.Resolved then
  1452. return self:_andThen(traceback, function(...)
  1453. return ...
  1454. end)
  1455. else
  1456. return Promise.reject(rejectionValue == nil and Error.new({
  1457. kind = Error.Kind.NotResolvedInTime,
  1458. error = "This Promise was not resolved in time for :now()",
  1459. context = ":now() was called at:\n\n" .. traceback,
  1460. }) or rejectionValue)
  1461. end
  1462. end
  1463.  
  1464. --[[
  1465. Retries a Promise-returning callback N times until it succeeds.
  1466. ]]
  1467. function Promise.retry(callback, times, ...)
  1468. assert(type(callback) == "function", "Parameter #1 to Promise.retry must be a function")
  1469. assert(type(times) == "number", "Parameter #2 to Promise.retry must be a number")
  1470.  
  1471. local args, length = {...}, select("#", ...)
  1472.  
  1473. return Promise.resolve(callback(...)):catch(function(...)
  1474. if times > 0 then
  1475. return Promise.retry(callback, times - 1, unpack(args, 1, length))
  1476. else
  1477. return Promise.reject(...)
  1478. end
  1479. end)
  1480. end
  1481.  
  1482. --[[
  1483. Converts an event into a Promise with an optional predicate
  1484. ]]
  1485. function Promise.fromEvent(event, predicate)
  1486. predicate = predicate or function()
  1487. return true
  1488. end
  1489.  
  1490. return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
  1491. local connection
  1492. local shouldDisconnect = false
  1493.  
  1494. local function disconnect()
  1495. connection:Disconnect()
  1496. connection = nil
  1497. end
  1498.  
  1499. -- We use shouldDisconnect because if the callback given to Connect is called before
  1500. -- Connect returns, connection will still be nil. This happens with events that queue up
  1501. -- events when there's nothing connected, such as RemoteEvents
  1502.  
  1503. connection = event:Connect(function(...)
  1504. local callbackValue = predicate(...)
  1505.  
  1506. if callbackValue == true then
  1507. resolve(...)
  1508.  
  1509. if connection then
  1510. disconnect()
  1511. else
  1512. shouldDisconnect = true
  1513. end
  1514. elseif type(callbackValue) ~= "boolean" then
  1515. error("Promise.fromEvent predicate should always return a boolean")
  1516. end
  1517. end)
  1518.  
  1519. if shouldDisconnect and connection then
  1520. return disconnect()
  1521. end
  1522.  
  1523. onCancel(disconnect)
  1524. end)
  1525. end
  1526.  
  1527. --[=[
  1528. Registers a callback that runs when an unhandled rejection happens. An unhandled rejection happens when a Promise
  1529. is rejected, and the rejection is not observed with `:catch`.
  1530.  
  1531. The callback is called with the actual promise that rejected, followed by the rejection values.
  1532.  
  1533. @param callback (promise: Promise, ...: any) -- A callback that runs when an unhandled rejection happens.
  1534. @return () -> () -- Function that unregisters the `callback` when called
  1535. ]=]
  1536. function Promise.onUnhandledRejection(callback)
  1537. table.insert(Promise._unhandledRejectionCallbacks, callback)
  1538.  
  1539. return function()
  1540. local index = table.find(Promise._unhandledRejectionCallbacks, callback)
  1541.  
  1542. if index then
  1543. table.remove(Promise._unhandledRejectionCallbacks, index)
  1544. end
  1545. end
  1546. end
  1547.  
  1548. return Promise
  1549.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement