Trying to get used to Promises, what can I improve?

(I’m using eryn’s Promise implementation as well as DataStore2)

i discovered Promises a few days ago and i am trying to get used to it, but i’m not sure if i’m doing it “right”.

so, i thought of a possible scenario in which i would use Promises: when a player buys an item.

i wrote an await() version and an andThen() version, but the await() version was so bad I realised there’s a reason andThen() exists. i mean, what’s the point of Promsies if you’re just going to yield with await()?

anyways, here is the code i wrote:
(assumed to be defined: player, price, giveItem)

local moneyData = DataStore2("Money", player)

moneyData:GetAsync()
    :andThen(function(money)
        if money >= price then
            return moneyData:IncrementAsync(-price)
        else
            return Promise.reject("not enough money")
        end
    end)
    :andThen(function()
        giveItem()
    end)
    :catch(function(err)
        warn("unable to buy item: " .. err)
    end)

is the structure for this code ok? am i right to use Promise.reject() if the player does not have enough money? is there any improvement i could make? should i make giveItem return a promise, and then return that promise in the andThen() function?

btw, for those unfamiliar with DataStore2, using GetAsync on a DataStore2 object only calls GetAsync on Roblox’s datastores if a cached value does not exist. else, it will just return the cached value

3 Likes

Whether or not getItem should return a promise is if it is an asynchronous operation.

As for code quality, it’s exceptional since you’re following the rather standard indentation of rules of both Lua and chain calls. All is good there.

I believe the only true issue is the use of Promise.reject. Instead, simply throw an error through error; this error will be caught by the :catch method.

1 Like

Looks good to me. Returning Promise.reject("str") is fine.

You could just do :andThen(giveItem) as a shorter version.

2 Likes