Created
April 2, 2013 13:54
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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