]> git.lizzy.rs Git - lua_async.git/blob - async_await.lua
Merge branch 'master' of https://github.com/EliasFleckenstein03/lua_async
[lua_async.git] / async_await.lua
1 local unpack = unpack or table.unpack
2
3 function async(func)
4         return function(...)
5                 local promise = Promise()
6                 promise.__on_resolve = func
7
8                 local args = {...}
9
10                 lua_async.resume(coroutine.create(function()
11                         promise:resolve(unpack(args))
12                 end))
13
14                 return promise
15         end
16 end
17
18 function await(promise)
19         local co = assert(coroutine.running(), "await called outside of an async function")
20
21         if promise.state == "pending" then
22                 promise:then_(function()
23                         lua_async.resume(co)
24                 end)
25
26                 coroutine.yield()
27         end
28
29         return unpack(promise.values)
30 end