I'm new to F# and stuck in understanding async in F# from the perspective of a C# developer. Say having the following snippet in C#:
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
How to write the same in F#?
You can use
async
:Just my two cents. But my understanding is that we should be handling the
HttpRequestException
when usingEnsureSuccessStatusCode()
.Below is the start of a module wrapping
HttpClient
that will buffer the response of a URL into astring
and safely wrap in aResult<'a, 'b>
for improved fault tolerance.Here is a function that should do what you're looking for (note that you'll have to wrap the code in an asynchronous computation expression in order to use the let! syntax):
You'll want to at least read and be aware of the established patterns in Http.fs if you're doing anything with
HttpClient
in F#.[See comments] TL;DR ... but Beware the Share. As noted by @pimbrouwers, it should be noted that you don't necessarily have to then use it though - subsetting and/or evolving your own set of helpers in your context can lead you to a better fitting abstraction (and bring you the benefits of the learning on the way).
To this point: It's considered idiomatic practice in F# to keep rarely used and/or overly specific helpers in a non-central location.