2021-08-06 13:54:20 -07:00
|
|
|
local unpack = unpack or table.unpack
|
|
|
|
|
2021-08-06 13:01:53 -07:00
|
|
|
function async(func)
|
|
|
|
return function(...)
|
|
|
|
local promise = Promise()
|
|
|
|
promise.__on_resolve = func
|
2021-08-06 10:19:23 -07:00
|
|
|
|
2021-08-06 13:01:53 -07:00
|
|
|
local args = {...}
|
2021-08-06 10:19:23 -07:00
|
|
|
|
2021-08-06 13:01:53 -07:00
|
|
|
lua_async.resume(coroutine.create(function()
|
|
|
|
promise:resolve(unpack(args))
|
|
|
|
end))
|
2021-08-06 10:19:23 -07:00
|
|
|
|
2021-08-06 13:01:53 -07:00
|
|
|
return promise
|
2021-08-06 10:19:23 -07:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
function await(promise)
|
|
|
|
local co = assert(coroutine.running(), "await called outside of an async function")
|
|
|
|
|
|
|
|
if promise.state == "pending" then
|
|
|
|
promise:then_(function()
|
|
|
|
lua_async.resume(co)
|
|
|
|
end)
|
|
|
|
|
|
|
|
coroutine.yield()
|
|
|
|
end
|
|
|
|
|
|
|
|
return unpack(promise.values)
|
|
|
|
end
|