Elixir/Phoenix多次尝试函数,捕捉:ok

问题描述:

我有一个函数ping(),导致{:ok}{:error}Elixir/Phoenix多次尝试函数,捕捉:ok

是否有可能使一个包装功能部件test(),将尝试ping() 5倍,返回一个错误之前,除非这些ping()之一,{:ok}回应?

如果test()可以从ping()第一次尝试返回{:ok},那么它应该退出递归,但如果没有,则继续尝试ping()另外4次。

我检查了try/catch,但似乎无法确定如何使其工作。任何提示赞赏!

这里不需要try/catch。用case声明匹配响应一个简单的递归函数就足够了:

defmodule A do 
    # A function that returns `{:ok}` a third of the times it's called. 
    def ping, do: if :random.uniform(3) == 1, do: {:ok}, else: {:error} 

    # 5 attempts. 
    def test(), do: test(5) 

    # If 1 attempt is left, just return whatever `ping` returns. 
    def test(1), do: ping() 
    # If more than one attempts are left. 
    def test(n) do 
    # Print remaining attempts for debugging. 
    IO.inspect {n} 
    # Call `ping`. 
    case ping() do 
     # Return {:ok} if it succeeded. 
     {:ok} -> {:ok} 
     # Otherwise recurse with 1 less attempt remaining. 
     {:error} -> test(n - 1) 
    end 
    end 
end 

测试:

iex(1)> A.test 
{5} 
{4} 
{3} 
{2} 
{:ok} 
iex(2)> A.test 
{5} 
{4} 
{3} 
{2} 
{:error} 
iex(3)> A.test 
{5} 
{:ok} 
iex(4)> A.test 
{5} 
{:ok} 
iex(5)> A.test 
{5} 
{4} 
{:ok} 
+0

谢谢您的回答!正是我在找什么。祝你今天愉快! – Ilya