Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created September 6, 2014 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/6963fcdf1551a81f9e3c to your computer and use it in GitHub Desktop.
Save hnakamur/6963fcdf1551a81f9e3c to your computer and use it in GitHub Desktop.
An example using uv.spawn with lua_promise
-- An example using uv.spawn with Promise.
-- (c) 2014 Hiroaki Nakamura
-- MIT license
--
-- Used libraries
-- * luv: https://github.com/luvit/luv
-- * lua_promise: https://github.com/friesencr/lua_promise
local uv = require("luv")
require("Promise")
function runCommand(command, args)
local p = Promise:new()
local options = {
stdio = {
nil,
1,
2
}
}
local child, pid = uv.spawn(command, args, options)
function child:onexit(code, signal)
uv.close(child)
p:resolve(code, signal)
end
p.child = child
p.pid = pid
return p
end
function after(ms)
local p = Promise:new()
local timer = uv.new_timer()
function timer:ontimeout()
uv.timer_stop(timer)
uv.close(timer)
p:resolve()
end
uv.timer_start(timer, ms, 0)
return p
end
local p = runCommand("sleep", {"3"})
p:done(function(code, signal)
print("sleep", "code", code, "signal", signal)
end)
:done(function()
runCommand("ls", {"-l"})
:done(function(code, signal)
print("ls", "code", code, "signal", signal)
end)
:done(function()
runCommand("pwd")
:done(function(code, signal)
print("pwd", "code", code, "signal", signal)
end)
end)
end)
after(1000)
:done(function()
uv.process_kill(p.child)
end)
repeat
until uv.run('once') == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment