Trouble With Multi-Threading

i have this function right here. it works just fine, but the execution can get a little slow at times.

local function getUserData(userId)
local success, name, thumbnail

success, name, thumbnail = pcall(function()
	local playerService = game:GetService("Players")
	local name = playerService:GetNameFromUserIdAsync(userId)
	local thumbnail = playerService:GetUserThumbnailAsync(userId, Enum.ThumbnailType.AvatarBust, Enum.ThumbnailSize.Size180x180)
	return name, thumbnail
end)

if success then
	return name, thumbnail
else
	print("error fetching user data: " .. tostring(name)) -- contains the error message
	return nil, nil
end

end

i am trying to implement multi-threading, but it just doesn’t work, it always returns an error, or nil. (one of my attempts can be seen below)

local function getUserData(userId)
local success, name, thumbnail

local function fetchData()
	local playerService = game:GetService("Players")
	success, name = pcall(function()
		name = playerService:GetNameFromUserIdAsync(userId)
	end)

	if success then
		success, thumbnail = pcall(function()
			thumbnail = playerService:GetUserThumbnailAsync(userId, Enum.ThumbnailType.AvatarBust, Enum.ThumbnailSize.Size180x180)
		end)
	end
end

local co = coroutine.create(fetchData)

task.spawn(function()
	coroutine.resume(co)

	if success then
		print("user data fetched successfully:", name, thumbnail)
	else
		print("error fetching user data.") -- this prints every time without fail!
	end
end)

return name, thumbnail

end

can anyone possibly point me in the right direction? i have no idea what i could be doing wrong.

Note, you aren’t just creating 1 thread, you are creating 2.

Also, please print the value of name variable in your error line. (As it gives you the comprehensive error message in a pcall that you definitely need when debugging)

i see. i’ll take that into consideration.

To run your function in a separate thread, it suffices to use task.spawn. task.spawn is identical to coroutine.resume(coroutine.create); you can try

task.spawn(fetchData)

Also, to help with debugging, either temporarily remove the pcalls or print the error message so you have a better understanding of what’s going wrong.

By the way, for working with asynchronous functions, I recommend using Promises for better error handling and control.

1 Like

i’ll certainly be looking into promises :+1:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.