aboutsummaryrefslogtreecommitdiff
path: root/async_await.lua
blob: 97d4f7d4706696c477233d53d0581af85e9c17b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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