Last active
November 29, 2020 04:08
-
-
Save howmanysmall/1c8498d916e79fff0b13e0e5afeaf9e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Promise = require(script.Parent.Parent.Vendor.Promise) | |
local function SafeWaitForChild(Parent, ChildName, Timeout) | |
return Promise.new(function(Resolve, Reject, OnCancel) | |
local Child = Parent:FindFirstChild(ChildName) | |
if Child then | |
Resolve(Child) | |
else | |
local Offset = Timeout or 5 | |
local StartTime = os.clock() | |
local Cancelled = false | |
local Connection | |
OnCancel(function() | |
Cancelled = true | |
if Connection then | |
Connection = Connection:Disconnect() | |
end | |
return Reject("SafeWaitForChild(" .. Parent:GetFullName() .. ", \"" .. tostring(ChildName) .. "\") was cancelled.") | |
end) | |
Connection = Parent:GetPropertyChangedSignal("Parent"):Connect(function() | |
if not Parent.Parent then | |
if Connection then | |
Connection = Connection:Disconnect() | |
end | |
Cancelled = true | |
return Reject("SafeWaitForChild(" .. Parent:GetFullName() .. ", \"" .. tostring(ChildName) .. "\") was cancelled.") | |
end | |
end) | |
repeat | |
Promise.Delay(0.03):Await() | |
Child = Parent:FindFirstChild(ChildName) | |
until Child or StartTime + Offset < os.clock() or Cancelled | |
if Connection then | |
Connection = Connection:Disconnect() | |
end | |
if not Timeout then | |
Reject("Infinite yield possible for SafeWaitForChild(" .. Parent:GetFullName() .. ", \"" .. tostring(ChildName) .. "\")") | |
elseif Child then | |
Resolve(Child) | |
end | |
end | |
end) | |
end | |
return SafeWaitForChild |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment