Skip to content

Instantly share code, notes, and snippets.

@ignacio
Created April 2, 2013 13:54
Show Gist options
  • Save ignacio/5292369 to your computer and use it in GitHub Desktop.
Save ignacio/5292369 to your computer and use it in GitHub Desktop.
await wrapper using coroutines (related to this gist: https://gist.github.com/creationix/5291866)
function await(continuation)
local coro = coroutine.running()
local result
local async
continuation(function(err, value)
if async == nil then
async = false
result = value
if err then error(err) end
return
end
if err then
-- todo, marshall the error into the coroutine
print(err)
else
coroutine.resume(coro, value)
end
end)
if async == nil then
async = true
return coroutine.yield()
end
return result
end
function sleep(ms)
return function(callback)
setTimeout(callback, ms)
end
end
coroutine.wrap(function()
for i=1, 10 do
console.log(i)
await(sleep(1000))
end
end)()
process:loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment