LPGhatguy / roblox-lua-promise

(NO LONGER MAINTAINED) An implementation of promises akin to JavaScript's Promises/A+
Creative Commons Zero v1.0 Universal
23 stars 4 forks source link

Roblox Lua Promise

An implementation of Promise similar to Promise/A+.

This project is no longer maintained. I recommend evaera's Promise implementation, which is a fork that implements cancellation and is actively maintained!

Motivation

I've found that being able to yield anywhere causes lots of bugs. In Rodux, I explicitly made it impossible to yield in a change handler because of the sheer number of bugs that occured when callbacks randomly yielded.

As such, I think that Roblox needs an object-based async primitive. It's not important to me whether these are Promises, Observables, Task objects, or Futures.

The important traits are:

This Promise implementation attempts to satisfy those traits.

API

Static Functions

Instance Methods

Example

This Promise implementation finished synchronously. In order to wrap an existing async API, you should use spawn or delay in order to prevent your calling thread from accidentally yielding.

local HttpService = game:GetService("HttpService")

-- A light wrapper around HttpService
-- Ideally, you do this once per project per async method that you use.
local function httpGet(url)
    return Promise.new(function(resolve, reject)
        -- Spawn to prevent yielding, since GetAsync yields.
        spawn(function()
            local ok, result = pcall(HttpService.GetAsync, HttpService, url)

            if ok then
                resolve(result)
            else
                reject(result)
            end
        end)
    end)
end

-- Usage
httpGet("https://google.com")
    :andThen(function(body)
        print("Here's the Google homepage:", body)
    end)
    :catch(function(err)
        warn("We failed to get the Google homepage!", err)
    end)

Future Additions

License

This project is available under the CC0 license. See LICENSE for details.