Help with UpdateASync()

Hi! Once again I am experiencing a few failures with my DataStore script once in a while (it won’t save properly). I have always been using SetASync() when updating a player’s stats, and so from now on I have heard that UpdateASync() may be the solution. Altough I have never used this technique before, so I am kinda uncertain on how it works, even after reading on the Developer Site. Anyways, here is my code so far, and it keeps printing “Failed saving” every time:

while true do
	for _,v in pairs(game:GetService("Players"):GetChildren()) do
		-- Saving:
		local key = "player-" .. v.UserId
		local playerStatsToSave = {v:WaitForChild("leaderstats"):WaitForChild("Rescues").Value, v:WaitForChild("leaderstats"):WaitForChild("Tokens").Value}
		local success, err = pcall(function()
			return stats:UpdateAsync(key, playerStatsToSave)
		end)
		if success then
			print("Successfully saved stats for " .. key)
		else
			print("Failed saving")
		end
    end
	wait(10)
end
1 Like

It’d be helpful to have the error you’re recieving. If you could get it to print the error returned from the pcall function and post it here, that’d be a great help to diagnosing the issue you’re facing.

From this it looks like you’re within the UpdateAsync limits, but are you using data stores anywhere else?

1 Like

Aaah right, it says “Unable to cast value to function”, and this is the only script in the game, it’s just a testing game for DataStore

Pcalls are lovely in the way that they return the error as a string as the second result if a call fails. Use that to your advantage.

local success, result = pcall(stats.UpdateAsync, stats, key, playerStatsToSave)

if success then
    print("Save success!")
else
    warn("Save failure:", result)
end

That aside, your call is failing because you’re using UpdateAsync with a table value. UpdateAsync requires a function. You can fix that up quickly by changing your value to return the table. There’s better ways to use UpdateAsync but for now, this is your fix relevant to the problem you’re having.

-- I'll use the code you put for easier reading, rather than using my style

local success, result = pcall(function()
    stats:UpdateAsync(key, function(old)
        return playerStatsToSave
    end)
end)
8 Likes

It works perfectly now! Thanks! :smiley: