Asynchronous 在elixir中启动节点进程,然后返回http请求的结果
使用,我希望执行以下操作:Asynchronous 在elixir中启动节点进程,然后返回http请求的结果,asynchronous,process,elixir,Asynchronous,Process,Elixir,使用,我希望执行以下操作: require HTTPoison alias Porcelain.Process, as: Proc alias Porcelain.Result, as: Res def request do cmd = "node node_app/src/index.js" opts = [out: {:send, self()}] proc = %Proc{pid: pid} = Porcelain.spawn_shell(cmd, opts) rec
require HTTPoison
alias Porcelain.Process, as: Proc
alias Porcelain.Result, as: Res
def request do
cmd = "node node_app/src/index.js"
opts = [out: {:send, self()}]
proc = %Proc{pid: pid} = Porcelain.spawn_shell(cmd, opts)
receive do
{^pid, :data, :out, log} ->
IO.puts "Node log => #{log}"
# only if log contains "running" should I send the request
if String.contains?(log, "running") do
IO.puts "Requesting..."
%HTTPoison.Response{body: body} = HTTPoison.get! @root_url <> "/collection"
Proc.stop(proc)
end
{^pid, :result, %Res{status: status} = res} ->
nil
end
Proc.await proc # wait for the process to terminate
body # return body of request
end
- 启动节点服务器
- 向节点进程发送http请求
- 关闭进程
- 返回请求的结果
require HTTPoison
alias Porcelain.Process, as: Proc
alias Porcelain.Result, as: Res
def request do
cmd = "node node_app/src/index.js"
opts = [out: {:send, self()}]
proc = %Proc{pid: pid} = Porcelain.spawn_shell(cmd, opts)
receive do
{^pid, :data, :out, log} ->
IO.puts "Node log => #{log}"
# only if log contains "running" should I send the request
if String.contains?(log, "running") do
IO.puts "Requesting..."
%HTTPoison.Response{body: body} = HTTPoison.get! @root_url <> "/collection"
Proc.stop(proc)
end
{^pid, :result, %Res{status: status} = res} ->
nil
end
Proc.await proc # wait for the process to terminate
body # return body of request
end
需要HTTPoison
别名瓷器。过程,如:Proc
别名瓷器。结果为:Res
def请求do
cmd=“node node\u app/src/index.js”
opts=[out:{:send,self()}]
proc=%proc{pid:pid}=ceral.spawn_shell(cmd,opts)
接收do
{^pid,:data,:out,log}->
IO.puts“节点日志=>{log}”
#只有当日志包含“running”时,我才应该发送请求
如果String.contains?(日志,“正在运行”)是否
IO.puts“请求…”
%HTTPoison.Response{body:body}=HTTPoison.get@根目录\ url“/集合”
进程停止(进程)
结束
{^pid,:结果,%Res{status:status}=Res}->
无
结束
Proc.wait Proc#等待进程终止
正文#返回请求正文
结束
一个问题是,我无法控制何时可以返回接收
我得到一个长生不老药的警告,身体可能不会被定义,这是我想要避免的
我走错方向了吗?有更好的方法吗
提前感谢您的帮助此代码有两个小问题:首先,在任何情况下都应该停止生成的进程 其次,您应该将
receive
的整个结果绑定到变量。类似的方法应该可以工作(未经测试):
result=receive do
{^pid,:data,:out,log}->
IO.puts“节点日志=>{log}”
#只有当日志包含“running”时,我才应该发送请求
如果String.contains?(日志,“正在运行”)是否
IO.puts“请求…”
HTTPoison.get@根目录\ url“/集合”
结束
{^pid,:结果,%Res{status:status}=Res}->
无
结束
进程停止(进程)
使用%HTTPoison.Response{body:body}