How do I wait until the function has ended? Or... I think that's the issue?

local pathFind = followPath(attack)


		--one final raycast to the player to determine if they are visible
		local ray = raycast(AIRoot, player.Character.HumanoidRootPart)
		print("Ray shot")
		if ray then
			if ray.Instance:FindFirstAncestor(player.Character.Name) then --if found,
				--continue
			else --if not, end the chase
				game.ReplicatedStorage.chaseMusicStop:FireClient(player) --stops music
			end
		end

The AI is supposed to pathfind to you when you are hidden.
“Ray shot” is printed, and the music is stopped, immediately after you are hidden.
I want it to wait until after the AI has reached it’s location, so I assume I have to wait until the function has ended.
Maybe?

Here’s the pathfinding thing, I just copied it from Roblox and it has worked fine so far.

local path = pathfindingService:CreatePath({
			AgentRadius = 3,
			AgentHeight = 6,
			AgentCanJump = false
		})
		local character = script.Parent
		local humanoid = character:WaitForChild("Humanoid")

		local waypoints
		local nextWaypointIndex
		local reachedConnection
		local blockedConnection

		local function followPath(destination)
			print("Searching...")
			-- Compute the path
			local success, errorMessage = pcall(function()
				path:ComputeAsync(character.PrimaryPart.Position, destination)
			end)

			if success and path.Status == Enum.PathStatus.Success then
				-- Get the path waypoints
				waypoints = path:GetWaypoints()

				-- Detect if path becomes blocked
				blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
					-- Check if the obstacle is further down the path
					if blockedWaypointIndex >= nextWaypointIndex then
						-- Stop detecting path blockage until path is re-computed
						blockedConnection:Disconnect()
						-- Call function to re-compute new path
						followPath(destination)
					end
				end)

				-- Detect when movement to next waypoint is complete
				if not reachedConnection then
					reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
						if reached and nextWaypointIndex < #waypoints then
							-- Increase waypoint index and move to next waypoint
							nextWaypointIndex += 1
							humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
						else
							reachedConnection:Disconnect()
							blockedConnection:Disconnect()
						end
					end)
				end

				-- Initially move to second waypoint (first waypoint is path start; skip it)
				nextWaypointIndex = 2
				humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
			else
				warn("Path not computed!", errorMessage)
			end
		end