如何访问 Promise<string> 的成功和错误?

huangapple go评论56阅读模式
英文:

How to access success and error of a Promise<string>?

问题

我有一个返回Promise&lt;string&gt;的API:

let response: Fable.Core.JS.Promise&lt;string&gt; = ApiClient.fetchGet &quot;https://google.com&quot;

我已经找到了如何处理其中的成功值:

response
    |&gt; Promise.iter (fun response -&gt;
        printf $&quot;{response}&quot;
    )

但是我该如何处理不仅成功字符串,还有错误字符串呢?

英文:

I have an API that returns Promise&lt;string&gt;:

let response: Fable.Core.JS.Promise&lt;string&gt; = ApiClient.fetchGet &quot;https://google.com&quot;

I figured out how to process a success value within it:

response
    |&gt; Promise.iter (fun response -&gt;
        printf $&quot;{response}&quot;
    )

But how could I process not only the success string, but an error string as well?

答案1

得分: 0

我找到了多种方法:使用 Result 类型、eitherEndmap/catchEnd

response
    |> Promise.result
    |> Promise.iter (fun res ->
        match res with
        | Ok success -> printfn $"success: {success}"
        | Error err -> printfn $"error: {err}"
    )
response
    |> Promise.eitherEnd
        (fun success -> printfn $"success: {success}")
        (fun err -> printfn $"error: {err}")
response
    |> Promise.map (fun success ->
        printfn $"success: {success}"
    )
    |> Promise.catchEnd (fun err ->
        printfn $"error: {err}"
    )
英文:

I've found multiple ways: using Result type, eitherEnd, map/catchEnd:

response
    |&gt; Promise.result
    |&gt; Promise.iter (fun res -&gt;
        match res with
        | Ok success -&gt; printfn $&quot;success: {success}&quot;
        | Error err -&gt; printfn $&quot;error: {err}&quot;
    )
response
    |&gt; Promise.eitherEnd
        (fun success -&gt; printfn $&quot;success: {success}&quot;)
        (fun err -&gt; printfn $&quot;error: {err}&quot;)
response
    |&gt; Promise.map (fun success -&gt;
        printfn $&quot;success: {success}&quot;
    )
    |&gt; Promise.catchEnd (fun err -&gt;
        printfn $&quot;error: {err}&quot;
    )

huangapple
  • 本文由 发表于 2023年7月11日 00:00:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定