Skip to content

Instantly share code, notes, and snippets.

@gdyr
Created December 12, 2019 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdyr/c607cedcbf38e1725eb782f9c1269811 to your computer and use it in GitHub Desktop.
Save gdyr/c607cedcbf38e1725eb782f9c1269811 to your computer and use it in GitHub Desktop.
Quick Lua Promises (v0.1)
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