Warning
This repository is archived. I've re-written Promises for YAPP, exported as yapp.class.Promise
This project comes from this Gist, which is also my code
LuaPromise aims to provide functionality similar to JavaScript's promises in Lua, allowing you to simplify async data flows and scrap the callback soup. You have to bring your own event loop, though synchronous code also works perfectly well with Promises.
The idea of Promises in Lua isn't new. If one of these libraries would work better for you, use it:
- Clone this repository
- See Building and Testing
local Promise = require("Promise")Promise(function (resolve, reject)
local success = true
if success then
resolve("Value1", "Value2")
else
reject("Failure!")
end
end)Promise.resolve("Value1", "Value2")
:after(function (value1, value2)
...
end)Promise.resolve()
:after(function ()
return Promise.resolve("Hello World!")
end)
:after(function(message)
print(message)
end)Promise.all({
Promise.resolve("Hello!")
Promise.resolve("Hola!")
})
:after(function (values)
-- Promise.all's resulting value is a table of tables.
-- in other words, an any[][]
for _, value in ipairs(values) do
print(value[1])
end
end)Promise.resolve()
:after(function ()
error("I did something stupid!")
end)
:after(function ()
-- this function won't get called, but automatically passes the error down
end)
:catch(function (err)
print(err)
end)Install to the user's luarocks directory:
luarocks make --local
Install globally
luarocks make
Both of these options provide the module Promise
lua test.lua
✔ Promise - 7 tests
✔ Promise()
✔ Promise.resolve()
✔ Promise.resolve(<value>)
✔ Promise.reject()
✔ Promise:after() throws an error
✔ Promise nesting
✔ Promise.all()
I also ran some (now removed, sorry!) async tests under AwesomeWM
✔ Async Promise
✔ Async Promise Rejection
✔ Async Promise Nesting
✔ Async Promise.all()
Async tests were completed using Awesome's awful.spawn.easy_async(). Note that LuaPromise doesn't provide an event loop, so an asynchronous function won't work in a standard lua runtime
- Synchronous JS Promises are inserted into the event loop, but Lua doesn't have an event loop to insert into
- Promises are still just tables
- To check if an instance is a Promise, check its metatable __index:
local is_promise = getmetatable(maybe_promise).__index == Promise
- Private members are only obfuscated by the
_privatesubtable. I'm leaving it up to you to not abuse it.
- To check if an instance is a Promise, check its metatable __index: