Why does SetAsync break the code?

  1. What do you want to achieve?
    Stop my code from breaking and have the datastore work.

  2. What is the issue?
    Every time this line of code is reached:-- cashDataStore:SetAsync(ID, cashmony) – nothing more happens after it and nothing is saved. Recently, for the first time it started working 50% of the time and reaching the final print statement indicating the function had compiled. Now it is back to the line stopping everything else.

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    So far I have added print statements around it to identify it as the issue. I have tried UpdateAsync but the pcall prints an error. I could not find any other reports such as this, though people on discord have described the same issue. I am not sure though if maybe I am doing something wrong.

local DataStoreService = game:GetService("DataStoreService")
local cashDataStore = DataStoreService:GetDataStore("cashDataStore")
local purchasesDS = DataStoreService:GetDataStore("DS")

function saveCash(player)
	local ID = "Cash_"..player.UserId
	print(ID)
	local cashmony = player.leaderstats.Cash.Value
	local success, errormessage = pcall(function()
		print("You had $" ..cashmony.." upon game exit")
		print("it")
		cashDataStore:SetAsync(ID, cashmony)
		print("After setasync")
		end)
		if success then
			print("worked")
		else
			print("There was an error when saving data")
		end
end

What is printed is: (It is also possible to print ID and cashmony. No error there)
17:42:28.371 Before savecash - Server - CoreScript:139
17:42:28.372 Cash_myid - Server - CoreScript:69
17:42:28.372 You had $327 upon game exit - Server - CoreScript:73
17:42:28.372 it - Server - CoreScript:74

Are you testing in studio? If so the test server could be shutting down before the data actually saves (you don’t have to worry about this happening in real servers 90% of the time).

What I suggest you do is switch to server mode → go to players → delete the player to simulate the player leaving. See if it saves.

If this wasn’t this case then please give more details.

4 Likes

Change it to a local function:

local function saveCash(player)
	local ID = "Cash_"..player.UserId
	print(ID)
	local cashmony = player.leaderstats.Cash.Value
	local success, errormessage = pcall(function()
		print("You had $" ..cashmony.." upon game exit")
		print("it")
		cashDataStore:SetAsync(ID, cashmony)
		print("After setasync")
	end)

	if success then
		print("worked")
	else
		print("There was an error when saving data")
	end
end

Output after changing it to a local function:
image

You need a function to load the data, not just save it. I’m not sure if this is an excerpt, but the function also needs to be called.

The function is called. Thats why he pasted his output.

1 Like