{"id":"jsdotlua/promise","name":"promise","scope":"jsdotlua","platform":"roblox","description":"Mirrored from the Wally registry.","version":"3.5.2","latest":"3.5.2","versions":["3.5.0","3.5.1","3.5.2"],"license":"MIT","licenseRating":"safe","licenseCaveats":[],"licenseVerified":true,"dependencies":{},"integrity":"475f3da931dd78208f43447abda955b388329bd0beb3ab8add86f9cf95428144","likes":0,"downloads":0,"install":"forest install jsdotlua/promise","url":"https://forest.dev/p/roblox/jsdotlua/promise","files":"https://api.forest.dev/ai/package/roblox/jsdotlua/promise/files","readme":"---\ntitle: Promise\ndocs:\n  desc: A Promise is an object that represents a value that will exist in the future, but doesn't right now. Promises allow you to then attach callbacks that can run once the value becomes available (known as *resolving*), or if an error has occurred (known as *rejecting*).\n\n  types:\n    - name: Status\n      desc: An enum value used to represent the Promise's status.\n      kind: enum\n      type:\n        Started:\n          desc: The Promise is executing, and not settled yet.\n        Resolved:\n          desc: The Promise finished successfully.\n        Rejected:\n          desc: The Promise was rejected.\n        Cancelled:\n          desc: The Promise was cancelled before it finished.\n\n  properties:\n    - name: Status\n      tags: [ 'read only', 'static', 'enums' ]\n      type: Status\n      desc: A table containing all members of the `Status` enum, e.g., `Promise.Status.Resolved`.\n\n\n  functions:\n    - name: new\n      desc: |\n        Construct a new Promise that will be resolved or rejected with the given callbacks.\n\n        If you `resolve` with a Promise, it will be chained onto.\n\n        You can safely yield within the executor function and it will not block the creating thread.\n\n        ```lua\n        local myFunction()\n          return Promise.new(function(resolve, reject, onCancel)\n            wait(1)\n            resolve(\"Hello world!\")\n          end)\n        end\n\n        myFunction():andThen(print)\n        ```\n\n        You do not need to use `pcall` within a Promise. Errors that occur during execution will be caught and turned into a rejection automatically. If `error()` is called with a table, that table will be the rejection value. Otherwise, string errors will be converted into `Promise.Error(Promise.Error.Kind.ExecutionError)` objects for tracking debug information.\n\n        You may register an optional cancellation hook by using the `onCancel` argument:\n          * This should be used to abort any ongoing operations leading up to the promise being settled.\n          * Call the `onCancel` function with a function callback as its only argument to set a hook which will in turn be called when/if the promise is cancelled.\n          * `onCancel` returns `true` if the Promise was already cancelled when you called `onCancel`.\n          * Calling `onCancel` with no argument will not override a previously set cancellation hook, but it will still return `true` if the Promise is currently cancelled.\n          * You can set the cancellation hook at any time before resolving.\n          * When a promise is cancelled, calls to `resolve` or `reject` will be ignored, regardless of if you set a cancellation hook or not.\n      static: true\n      params:\n        - name: executor\n          type:\n            kind: function\n            params:\n              - name: resolve\n                type:\n                  kind: function\n                  params:\n                    - name: \"...\"\n                      type: ...any?\n                  returns: void\n              - name: reject\n                type:\n                  kind: function\n                  params:\n                    - name: \"...\"\n                      type: ...any?\n                  returns: void\n              - name: onCancel\n                type:\n                  kind: function\n                  params:\n                    - name: abortHandler\n                      kind: function\n                  returns:\n                    - type: boolean\n                      desc: \"Returns `true` if the Promise was already cancelled at the time of calling `onCancel`.\"\n      returns: Promise\n    - name: defer\n      since: 3.0.0\n      desc: |\n        The same as [[Promise.new]], except execution begins after the next `Heartbeat` event.\n\n        This is a spiritual replacement for `spawn`, but it does not suffer from the same [issues](https://eryn.io/gist/3db84579866c099cdd5bb2ff37947cec) as `spawn`.\n\n        ```lua\n        local function waitForChild(instance, childName, timeout)\n          return Promise.defer(function(resolve, reject)\n            local child = instance:WaitForChild(childName, timeout)\n\n            ;(child and resolve or reject)(child)\n          end)\n        end\n        ```\n\n      static: true\n      params:\n        - name: deferExecutor\n          type:\n            kind: function\n            params:\n              - name: resolve\n                type:\n                  kind: function\n                  params:\n                    - name: \"...\"\n                      type: ...any?\n                  returns: void\n              - name: reject\n                type:\n                  kind: function\n                  params:\n                    - name: \"...\"\n                      type: ...any?\n                  returns: void\n              - name: onCancel\n                type:\n                  kind: function\n                  params:\n                    - name: abortHandler\n                      kind: function\n                  returns:\n                    - type: boolean\n                      desc: \"Returns `true` if the Promise was already cancelled at the time of calling `onCancel`.\"\n      returns: Promise\n\n    - name: try\n      desc: |\n        Begins a Promise chain, calling a function and returning a Promise resolving with its return value. If the function errors, the returned Promise will be rejected with the error. You can safely yield within the Promise.try callback.\n\n        ::: tip\n        `Promise.try` is similar to [[Promise.promisify]], except the callback is invoked immediately instead of returning a new function.\n        :::\n\n        ```lua\n        Promise.try(function()\n          return math.random(1, 2) == 1 and \"ok\" or error(\"Oh an error!\")\n        end)\n          :andThen(function(text)\n            print(text)\n          end)\n          :catch(function(err)\n            warn(\"Something went wrong\")\n          end)\n        ```\n      static: true\n      params:\n        - name: callback\n          type:\n            kind: function\n            params: \"...: ...any?\"\n            returns: \"...any?\"\n        - name: \"...\"\n          type: \"...any?\"\n          desc: Arguments for the callback\n      returns:\n        - type: \"Promise<...any?>\"\n          desc: The return value of the passed callback.\n\n    - name: promisify\n      desc: |\n        Wraps a function that yields into one that returns a Promise.\n\n        Any errors that occur while executing the function will be turned into rejections.\n\n        ::: tip\n        `Promise.promisify` is similar to [[Promise.try]], except the callback is returned as a callable function instead of being invoked immediately.\n        :::\n\n        ```lua\n        local sleep = Promise.promisify(wait)\n\n        sleep(1):andThen(print)\n        ```\n\n        ```lua\n        local isPlayerInGroup = Promise.promisify(function(player, groupId)\n          return player:IsInGroup(groupId)\n        end)\n        ```\n      static: true\n      params:\n        - name: callback\n          type:\n            kind: function\n            params: \"...: ...any?\"\n      returns:\n        - desc: The function acts like the passed function but now returns a Promise of its return values.\n          type:\n            kind: function\n            params:\n              - name: \"...\"\n                type: \"...any?\"\n                desc: The same arguments the wrapped function usually takes.\n            returns:\n              - name: \"*\"\n                desc: The return values from the wrapped function.\n\n    - name: resolve\n      desc: Creates an immediately resolved Promise with the given value.\n      static: true\n      params: \"value: ...any\"\n      returns: Promise<...any>\n    - name: reject\n      desc: |\n        Creates an immediately rejected Promise with the given value.\n\n        ::: tip\n        Someone needs to consume this rejection (i.e. `:catch()` it), otherwise it will emit an unhandled Promise rejection warning on the next frame. Thus, you should not create and store rejected Promises for later use. Only create them on-demand as needed.\n        :::\n\n        ```lua\n          -- Example using Promise.resolve to deliver cached values:\n          function getSomething(name)\n            if cache[name] then\n              return Promise.resolve(cache[name])\n            else\n              return Promise.new(function(resolve, reject)\n                local thing = getTheThing()\n                cache[name] = thing\n\n                resolve(thing)\n              end)\n            end\n          end\n        ```\n      static: true\n      params: \"value: ...any\"\n      returns: Promise<...any>\n\n    - name: all\n      desc: |\n        Accepts an array of Promises and returns a new promise that:\n          * is resolved after all input promises resolve.\n          * is rejected if *any* input promises reject.\n\n        Note: Only the first return value from each promise will be present in the resulting array.\n\n        After any input Promise rejects, all other input Promises that are still pending will be cancelled if they have no other consumers.\n\n        ```lua\n          local promises = {\n            returnsAPromise(\"example 1\"),\n            returnsAPromise(\"example 2\"),\n            returnsAPromise(\"example 3\"),\n          }\n\n          return Promise.all(promises)\n        ```\n      static: true\n      params: \"promises: array<Promise<T>>\"\n      returns: Promise<array<T>>\n\n    - name: allSettled\n      desc: |\n        Accepts an array of Promises and returns a new Promise that resolves with an array of in-place Statuses when all input Promises have settled. This is equivalent to mapping `promise:finally` over the array of Promises.\n\n        ```lua\n          local promises = {\n            returnsAPromise(\"example 1\"),\n            returnsAPromise(\"example 2\"),\n            returnsAPromise(\"example 3\"),\n          }\n\n          return Promise.allSettled(promises)\n        ```\n      static: true\n      params: \"promises: array<Promise<T>>\"\n      returns: Promise<array<Status>>\n\n    - name: race\n      desc: |\n        Accepts an array of Promises and returns a new promise that is resolved or rejected as soon as any Promise in the array resolves or rejects.\n\n        ::: warning\n        If the first Promise to settle from the array settles with a rejection, the resulting Promise from `race` will reject.\n\n        If you instead want to tolerate rejections, and only care about at least one Promise resolving, you should use [[Promise.any]] or [[Promise.some]] instead.\n        :::\n\n        All other Promises that don't win the race will be cancelled if they have no other consumers.\n\n        ```lua\n          local promises = {\n            returnsAPromise(\"example 1\"),\n            returnsAPromise(\"example 2\"),\n            returnsAPromise(\"example 3\"),\n          }\n\n          return Promise.race(promises) -- Only returns 1st value to resolve or reject\n        ```\n      static: true\n      params: \"promises: array<Promise<T>>\"\n      returns: Promise<T>\n\n    - name: some\n      desc: |\n        Accepts an array of Promises and returns a Promise that is resolved as soon as `count` Promises are resolved from the input array. The resolved array values are in the order that the Promises resolved in. When this Promise resolves, all other pending Promises are cancelled if they have no other consumers.\n\n        `count` 0 results in an empty array. The resultant array will never have more than `count` elements.\n\n        ```lua\n          local promises = {\n            returnsAPromise(\"example 1\"),\n            returnsAPromise(\"example 2\"),\n            returnsAPromise(\"example 3\"),\n          }\n\n          return Promise.some(promises, 2) -- Only resolves with first 2 promises to resolve\n        ```\n      static: true\n      params: \"promises: array<Promise<T>>, count: number\"\n      returns: Promise<array<T>>\n\n    - name: any\n      desc: |\n        Accepts an array of Promises and returns a Promise that is resolved as soon as *any* of the input Promises resolves. It will reject only if *all* input Promises reject. As soon as one Promises resolves, all other pending Promises are cancelled if they have no other consumers.\n\n        Resolves directly with the value of the first resolved Promise. This is essentially [[Promise.some]] with `1` count, except the Promise resolves with the value directly instead of an array with one element.\n\n        ```lua\n          local promises = {\n            returnsAPromise(\"example 1\"),\n            returnsAPromise(\"example 2\"),\n            returnsAPromise(\"example 3\"),\n          }\n\n          return Promise.any(promises) -- Resolves with first value to resolve (only rejects if all 3 rejected)\n        ```\n\n      static: true\n      params: \"promises: array<Promise<T>>\"\n      returns: Promise<T>\n\n    - name: delay\n      desc: |\n        Returns a Promise that resolves after `seconds` seconds have passed. The Promise resolves with the actual amount of time that was waited.\n\n        This function is **not** a wrapper around `wait`. `Promise.delay` uses a custom scheduler which provides more accurate timing. As an optimization, cancelling this Promise instantly removes the task from the scheduler.\n\n        ::: warning\n          Passing `NaN`, infinity, or a number less than 1/60 is equivalent to passing 1/60.\n        :::\n\n        ```lua\n          Promise.delay(5):andThenCall(print, \"This prints after 5 seconds\")\n        ```\n      params: \"seconds: number\"\n      returns: Promise<number>\n      static: true\n\n    - name: fold\n      since: 3.1.0\n      desc: |\n        Folds an array of values or promises into a single value. The array is traversed sequentially.\n\n        The reducer function can return a promise or value directly. Each iteration receives the resolved value from the previous, and the first receives your defined initial value.\n\n        The folding will stop at the first rejection encountered.\n        ```lua\n        local basket = {\"blueberry\", \"melon\", \"pear\", \"melon\"}\n        Promise.fold(basket, function(cost, fruit)\n          if fruit == \"blueberry\" then\n            return cost -- blueberries are free!\n          else\n            -- call a function that returns a promise with the fruit price\n            return fetchPrice(fruit):andThen(function(fruitCost)\n              return cost + fruitCost\n            end)\n          end\n        end, 0)\n        ```\n      params:\n        - name: list\n          type: \"array<T | Promise<T>>\"\n        - name: reducer\n          desc: The function to call with the accumulated value, the current element from the array and its index.\n          type:\n            kind: function\n            params: \"accumulator: U, value: T, index: number\"\n            returns: U | Promise<U>\n        - name: initialValue\n          type: \"U\"\n      returns: Promise<U>\n      static: true\n\n    - name: each\n      since: 3.0.0\n      desc: |\n        Iterates serially over the given an array of values, calling the predicate callback on each value before continuing.\n\n        If the predicate returns a Promise, we wait for that Promise to resolve before moving on to the next item\n        in the array.\n\n        ::: tip\n        `Promise.each` is similar to `Promise.all`, except the Promises are ran in order instead of all at once.\n\n        But because Promises are eager, by the time they are created, they're already running. Thus, we need a way to defer creation of each Promise until a later time.\n\n        The predicate function exists as a way for us to operate on our data instead of creating a new closure for each Promise. If you would prefer, you can pass in an array of functions, and in the predicate, call the function and return its return value.\n        :::\n\n        ```lua\n        Promise.each({\n          \"foo\",\n          \"bar\",\n          \"baz\",\n          \"qux\"\n        }, function(value, index)\n          return Promise.delay(1):andThen(function()\n            print((\"%d) Got %s!\"):format(index, value))\n          end)\n        end)\n\n        --[[\n          (1 second ","readmeTruncated":true,"readmeFull":"https://api.forest.dev/v1/package/jsdotlua/roblox/promise/3.5.2/readme"}