diff options
author | Elias Fleckenstein <eliasfleckenstein@web.de> | 2021-08-06 19:19:23 +0200 |
---|---|---|
committer | Elias Fleckenstein <eliasfleckenstein@web.de> | 2021-08-06 19:19:23 +0200 |
commit | a2770298f040307f8dd59c7a88d7e40d37faec14 (patch) | |
tree | 3ce0ec0c31be5b2f87c086488973e8957acf84ad /async_await.lua | |
parent | f6cc945b08e5a89492d92a88a7146da421e42819 (diff) | |
download | lua_async-a2770298f040307f8dd59c7a88d7e40d37faec14.tar.xz |
Add source code
Diffstat (limited to 'async_await.lua')
-rw-r--r-- | async_await.lua | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/async_await.lua b/async_await.lua new file mode 100644 index 0000000..97d4f7d --- /dev/null +++ b/async_await.lua @@ -0,0 +1,43 @@ +lua_async.async_await = {} + +function lua_async.resume(co) + local status, err = coroutine.resume(co) + + if coroutine.status(co) == "dead" or err then + lua_async.limiting.unset_limit(co) + end + + if not status then + error("Error (in async function): " .. err) + 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 + +function async(func) + return function(...) + local promise = Promise() + promise.__on_resolve = func + + local args = {...} + + lua_async.resume(coroutine.create(function() + promise:resolve(unpack(args)) + end)) + + return promise + end +end + |