Skip to content

Instantly share code, notes, and snippets.

@sinkingsugar
Forked from ignacio/await.lua
Created October 15, 2015 06:22
Show Gist options
  • Save sinkingsugar/70f2defb5c92c5434dc3 to your computer and use it in GitHub Desktop.
Save sinkingsugar/70f2defb5c92c5434dc3 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