Skip to content

Commit 5aa4b4e

Browse files
committed
Improve async
1 parent a055dab commit 5aa4b4e

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

src/std.lua

+14-15
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
local path = jsRequire("path")
22
local fs = jsRequire("fs")
33

4-
function tick(co)
5-
if coroutine.status(co) == "suspended" then
6-
coroutine.resume(co)
7-
setImmediate(tick, co)
8-
end
9-
end
10-
114
-- async function to bound awaits
125
function async(callback)
136
return function(...)
14-
local varargs = {...}
7+
local co = coroutine.create(callback)
8+
local safe, result = coroutine.resume(co, ...)
159

1610
return Promise.create(function(resolve, reject)
17-
local co = coroutine.create(function()
18-
local safe, args = pcall(callback, table.unpack(varargs))
11+
local function step()
12+
if coroutine.status(co) == "dead" then
13+
local send = safe and resolve or reject
14+
return send(result)
15+
end
16+
17+
safe, result = coroutine.resume(co)
1918

20-
if safe then
21-
resolve(args)
19+
if safe and result == Promise.resolve(result) then
20+
result:finally(step)
2221
else
23-
reject(args)
22+
step()
2423
end
25-
end)
24+
end
2625

27-
tick(co)
26+
result:finally(step)
2827
end)
2928
end
3029
end

0 commit comments

Comments
 (0)