For loop does not wait for function to complete in a for loop

Hi, I am trying to allow for a function to fully complete before the next iteration in the for loop, there have been some other posts but all outline methods for while loops that dont work the best for for loops.

Here is the code

script.Parent.MouseButton1Click:Connect(function()
	if debounce == true then
		debounce = false
		for i, v in pairs(items) do
			print("Looped.")
			MarketplaceService:PromptPurchase(player, v)

			MarketplaceService.PromptPurchaseFinished:Connect(function(player, assetId, isPurchased)
				if isPurchased then
					
					-- Sends receipt
					game:GetService("ReplicatedStorage").SendWebhookMessage:FireServer(player.Name, localPlayer.UserId, v, GetProductPrice(v))

					-- Removes item from list
					script.Parent.Parent.Parent.Items:WaitForChild(v):Destroy()
					table.remove(items, v)
					print("Purchase complete")
				else
					print("Purchase failed.")
				end
			end)	
		end
		debounce = true
	end
end)

Here is the output I am receiving
2x Looped indicates the loop has ran twice since there are 2 items in the table - but the for loop has not waited for the function to complete
image

2x Purchase complete and performs function on both items incorrectly
image

1 Like

When you :Connect a function the thread keeps on running.

What you want to do is use PromptPurchaseFinished:Wait() this will yield the thread until the event is called.

That is the cause of the loop running twice. But in this context you will have another problem. PrompPurchaseFinished fires for any player buying something.

It looks like this code is in a Gui, that means it will be replicated to every player. It is typically much better to handle purchases from a single server script that you would put in ServerScriptService.

1 Like

Won’t it also make a new :connect listener for each iteration, so the 2nd loop will fire 2 connect functions, then 3 , etc…

I don’t really know what you are referring to. When you say “fire”, I think you mean connect.

Each iteration of the loop will connect a function with the current code. The loop will not wait for the event to fire though. It will immediately go through all iterations of the loop in a single heartbeat.

Using RbxScriptSignal:Wait() will yield the code.

Right thats what I mean. But the loop will create new :connect each loop so you’ll have duplicate functions connected.

idk, maybe

Thank you for explaining that its all sorted now thanks!

1 Like

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