Created
December 12, 2019 06:11
-
-
Save gdyr/c607cedcbf38e1725eb782f9c1269811 to your computer and use it in GitHub Desktop.
Quick Lua Promises (v0.1)
This file contains 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
Promise = (function(asyncFunction) | |
local state = 'pending'; | |
local result; | |
local rListen, eListen = {}, {}; | |
asyncFunction(function(...) | |
for _,f in pairs(rListen) do | |
f(...); | |
end; | |
end, function(err) | |
for _,f in pairs(eListen) do | |
f(err) | |
end | |
end); | |
return setmetatable({ | |
next = function(promise, nextFunction, errorFunction) | |
return Promise(function(resolve, reject) | |
local function nf(r) resolve(nextFunction(r)); end; | |
if(state == 'resolved' and type(nextFunction) == 'function') then nf(table.unpack(result)); end; | |
if(state == 'error' and type(errorFunction) == 'function') then errorFunction(table.unpack(result)); end; | |
if(state == 'pending') then | |
table.insert(rListen, nf); | |
table.insert(eListen, errorFunction); | |
end; | |
end); | |
end | |
}, { | |
__tostring = function(t) | |
return('promise: ' .. tostring(asyncFunction):match(': (.*)')); | |
end | |
}); | |
end); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment