Skip to content
This repository has been archived by the owner on Jul 28, 2022. It is now read-only.

Commit

Permalink
Data promises
Browse files Browse the repository at this point in the history
  • Loading branch information
Sleitnick committed May 9, 2019
1 parent db1d31a commit 1aaa261
Show file tree
Hide file tree
Showing 2 changed files with 291 additions and 119 deletions.
34 changes: 26 additions & 8 deletions src/ReplicatedStorage/Aero/Shared/Promise.lua
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
promise:Then(handler)
promise:Catch(handler)
promise:Finally(handler)
promise:GetStatus()
--]]

Expand Down Expand Up @@ -160,6 +163,7 @@ function Promise.new(callback, forceSpawn)
-- Queues representing functions we should invoke when we update!
_queuedResolve = {};
_queuedReject = {};
_queuedFinally = {};
}

setmetatable(self, Promise)
Expand Down Expand Up @@ -268,14 +272,10 @@ end
Is the given object a Promise instance?
]]
function Promise.Is(object)
if (type(object) ~= "table") then
return false
end

return object[PromiseMarker] == true
return (type(object) == "table" and object[PromiseMarker] == true)
end

function Promise.prototype:getStatus()
function Promise.prototype:GetStatus()
return self._status
end

Expand Down Expand Up @@ -323,6 +323,18 @@ function Promise.prototype:Catch(failureCallback)
return self:Then(nil, failureCallback)
end

--[[
Used to handle the end of a promise, whether it succeeded or failed.
]]
function Promise.prototype:Finally(finallyCallback)
if (self._status == Promise.Status.Started) then
table.insert(self._queuedFinally, finallyCallback)
else
spawn(finallyCallback)
end
return self
end

--[[
Yield until the promise is completed.
Expand Down Expand Up @@ -409,9 +421,12 @@ function Promise.prototype:_resolve(...)
self._valuesLength, self._values = pack(...)

-- We assume that these callbacks will not throw errors.
for _, callback in ipairs(self._queuedResolve) do
for _, callback in pairs(self._queuedResolve) do
callback(...)
end
for _, callback in pairs(self._queuedFinally) do
spawn(callback)
end
end

function Promise.prototype:_reject(...)
Expand All @@ -425,7 +440,7 @@ function Promise.prototype:_reject(...)
-- If there are any rejection handlers, call those!
if (not isEmpty(self._queuedReject)) then
-- We assume that these callbacks will not throw errors.
for _, callback in ipairs(self._queuedReject) do
for _, callback in pairs(self._queuedReject) do
callback(...)
end
else
Expand All @@ -451,6 +466,9 @@ function Promise.prototype:_reject(...)
warn(message)
end)
end
for _, callback in pairs(self._queuedFinally) do
spawn(callback)
end
end

return Promise
Loading

0 comments on commit 1aaa261

Please sign in to comment.