Advertisement
qsenko1

Roblox Promise Warn scrip?

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