SetAsync sometimes works, sometimes not

I’m going crazy here trying to understand what happens to SetASync. I am starting the first tests to record game data in DataStore. But it is not being easy.

I’m using Studio:

  • Game Settings->Options->Enable Studio Access to API Services = ON.
  • All plugins disabled.
  • Beta features too.

The code below is simple: when the user enters the game, he loads the content of a numeric variable “a”. And when the user leaves the game, he adds 1 to this variable and writes with SetASync:

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local playerUserId
local data
local playerData = DataStoreService:GetDataStore("PlayerData")
 
Players.PlayerAdded:Connect(function(player)
	playerUserId = "Player_" .. player.UserId
	print('------- PlayerAdded --------')
	print(playerUserId)
	data = playerData:GetAsync(playerUserId)
	if data then
		print '*** data found:'
		for key, value in pairs(data) do
		    print(key, value)
		end
	else
		print('no data. set a=0')
		data = {a=0}
	end
end)
 
Players.PlayerRemoving:Connect(function(player)
	print('------- PlayerRemoving --------')
	print(playerUserId)
	data.a = data.a + 1
	for key, value in pairs(data) do
	    print(key, value)
	end
	playerData:SetAsync(playerUserId, data)
	print('ok')
end)

… and what I mean by “SetAsync sometimes works, sometimes not…”:

If I play (F5) one time I get:

  ------- PlayerAdded --------
  Player_1110384526
  *** data found:
  a 4

which means that the game found a previous variable “a” with the value = 4.

So I stop the game and I get:

  ------- PlayerRemoving --------
  a 5
  ok

here the value of “a” should be recorded by SetASync with 5.

If I press F5 right away, without waiting many seconds, SOMETIMES the value is NOT updated… and sometimes it IS updated…

So I think there is a problem with the Roblox Servers?

1 Like

This is common in studio I think, people recommend using BindToClose. But that still doesn’t work for me sometimes. I guess the server shuts down (you stopping the game) and doesn’t give datastore enough time to make it’s HTTP request, especially if it’s a good sized array. That’s what I think.

1 Like

yes, this is what happens in studio, the client server might shut down too quick for the data store to actually update. Just like @MightTea said, try to use BindToClose if your server were to crash .

When I was about to give up, I was told about DataStore2.
Blessed be its creator. :grinning:
Simple, objective, and efficient.
No more trouble saving player data.

1 Like