(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