Here is a client side Fable.Remoting example that prints the result of an async function.
// Client code (Compiled to Javascript using Fable)
// ============
open Fable.Remoting.Client
let server = Proxy.create<IServer>
async {
let! length = server.getLength “hello”
do printfn “%d” length // 5
}
|> Async.StartImmediate
How do I get the length
value?
I see you've tagged your question with elmish, so I'm going to assume you have a
Msg
type defined. Don't useAsync.StartImmediate
orAsync.RunSynchronously
; in Elmish, you should useCmd.OfAsync
to schedule a message to be dispatched once the async block returns a value. There are four functions inCmd.OfAsync
(and the same four appear inCmd.OfPromise
as well):either
,perform
,attempt
, andresult
. I'll break them down for you since their documentation isn't quite up to snuff yet:either
: takes four parameters,task
,arg
,ofSuccess
, andofError
.task
is the async function you want to call (of type'a -> Async<'b>
).arg
is the parameter of type'a
that you want to pass to thetask
function.ofSuccess
is a function of type'b -> 'Msg
: it will receive the result of the async function and is supposed to create a message, presumably one that incorporates the'b
result. Finally,ofError
is a function of typeexn -> 'Msg
: if thetask
function throws an exception, thenofError
will be called instead ofofSuccess
, and is supposed to turn that exception into an Elmish message that your code can handle (presumably one that will log an error to the Javascript console or pop up a notification with Thoth.Toast or something like that).perform
: likeeither
but there's noofError
parameter. Use this if your async command cannot fail (which is never the case with remote API calls, as it's always possible the network is down or your server is unresponsive), or if you just don't care about exceptions and don't mind an unhandled exception getting thrown.attempt
: likeeither
but there's noofSuccess
parameter, so thetask
function's result will be ignored if it succeeds.result
: this one is completely different. It just takes a single parameter of typeAsync<'Msg>
, i.e. you pass it anasync
block that is already going to produce a message.With the code you've written, you would use
Cmd.OfAsync.result
if you wanted to make minimal changes to your code, but I would suggest usingCmd.OfAsync.perform
instead (and upgrading it toCmd.OfAsync.either
once you have written some error-handling code). I'll show you both ways:And if you were using
either
(which you really should do once you go to production), there would be a third messageLogError of exn
that would be handled like:and the
Cmd.OfAsync.perform
line in the code above would become:That's the right way to handle async-producing functions in Elmish.