-
Notifications
You must be signed in to change notification settings - Fork 0
/
async.lua
54 lines (48 loc) · 1.16 KB
/
async.lua
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
44
45
46
47
48
49
50
51
52
53
54
local function await(p)
assert(coroutine.running(), "running inside a Promise.async() call")
local result = nil
local err = nil
local finished = false
p:next(function(...)
result = {...}
finished = true
end, function(e)
err = e
finished = true
end)
while true do
if finished then
if err then
return nil, err
else
return unpack(result)
end
else
coroutine.yield()
end
end
end
function Promise.async(fn)
local t = coroutine.create(fn)
local p = Promise.new()
local step = nil
local result = nil
local cont = nil
local _ = nil
step = function()
if coroutine.status(t) == "suspended" then
cont, result = coroutine.resume(t, await)
if not cont then
-- error in first async() level
p:reject(result)
return
end
minetest.after(0, step)
else
-- last result from resume was the return value
p:resolve(result)
end
end
step()
return p
end