英文:
How to access success and error of a Promise<string>?
问题
我有一个返回Promise<string>
的API:
let response: Fable.Core.JS.Promise<string> = ApiClient.fetchGet "https://google.com"
我已经找到了如何处理其中的成功值:
response
|> Promise.iter (fun response ->
printf $"{response}"
)
但是我该如何处理不仅成功字符串,还有错误字符串呢?
英文:
I have an API that returns Promise<string>
:
let response: Fable.Core.JS.Promise<string> = ApiClient.fetchGet "https://google.com"
I figured out how to process a success value within it:
response
|> Promise.iter (fun response ->
printf $"{response}"
)
But how could I process not only the success string, but an error string as well?
答案1
得分: 0
我找到了多种方法:使用 Result
类型、eitherEnd
、map
/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
|> 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}"
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论