Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I know when UpdateAsync is the method I need to use?

When using datastores I always use :SetAsync and pretty much every tutorial out there says that I should use :UpdateAsync. The thing is, after reading the description of what it does I was mildly confused as to why it was important. In my game as of right now I will not need to get the old value in the datastore. Someone mentioned that if you are worried about a datastore updating from two different places or something like that, you should use UpdateAsync. I am so confused as to why I would benefit by using :UpdateAsync. Any help would be much appreciated. Thanks!

1 comment

2 answers

✓ Accepted answer

According to Roblox,

#####Retrieves the value of the key from the website, and updates it with a new value. This function validates the data and must therefore be the standard function to edit data when there is a chance more than one server can edit the same data at the same time. #####The value returned by this function is the new value, returned once the altered data is properly saved.

#####The second parameter of UpdateAsync is a function you need to provide that takes the key's old value as input and return the new value. After the function is called, the key is set to the new value.

-- Example script:

local DataStoreService = game:GetService("DataStoreService")
local CashSave = DataStoreService:GetDataStore("CashSave")

local function newVal(oldVal)
    local new = oldVal or 0 -- possible that oldVal could be nil

    new = new + 25 -- give 25 cash to users each time they visit..?
end
 
game:GetService("Players").PlayerAdded:Connect(function(plr)
	local key = "Player_" .. plr.UserId 

	CashSave:UpdateAsync(key, newVal)
end)

1 comment

0

How do I know if it has the possibility to be changed from more than one server. If it does how does it help me to use updateasync?

UpdateAsync is generally considered better because it's a bit faster than SetAsync. It also allows you to look at the old value before you overwrite it with a new one just in case something "doesn't seem right". You don't actually need to use the old value that UpdateAsync takes as a parameter, you could just ignore it all together. That being said, you could use another form of Datastores that actually doesn't use UpdateAsync at all - which is a spin off of Berezaa's method of saving.

https://devforum.roblox.com/t/how-to-use-datastore2-data-store-caching-and-data-loss-prevention/136317

3 comments

0

Another form of datstores?

0

Oh I kind of see...

0

But to answer your question better, update (didn't have a ton of time), UpdateAsync is for when you already have data set to a Key, and you are just updating it.

This discussion is preserved as it was. New answers, comments, and votes are closed.