Created
July 22, 2014 12:28
-
-
Save zserge/b027eb29293e2a499700 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-- | |
-- Let you write code like | |
-- chain(func1):next(func2):next(func3):go() | |
-- | |
function chain(cb) | |
local queue = {} | |
local n, go; | |
go = function() | |
local cb = table.remove(queue, 1) | |
if cb then cb(go) end | |
end | |
n = { | |
next = function(a1, a2) | |
local cb = a2 or a1 | |
table.insert(queue, cb) | |
return { | |
next = n.next, | |
go = go | |
} | |
end, | |
go = go | |
} | |
return n.next(cb) | |
end | |
-- | |
-- Example | |
-- | |
local c = chain(function(done) | |
print('X') | |
done() | |
end):next(function(done) | |
print('Y') | |
done() | |
end):next(function(done) | |
print('Z') | |
done() | |
end):go() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment