How do I await an async method in F#?
I have the following code:
type LegoExample() =
let brick = Brick(BluetoothCommunication("COM3"))
let! result = brick.ConnectAsync();
Error:
Unexpected binder keyword in member definition
Note, I reviewed the following link:
However, I only observe the functional technique and not the OOP technique.
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.
Await Syntax The keyword await before a function makes the function wait for a promise: let value = await promise; The await keyword can only be used inside an async function.
async function f() { return 1; } The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
you get the error because the let!
construct (just like the do!
) needs to be placed inside a computational workflow (like async { ...}
but there are others - it's basically the syntactic sugar F# gives you for monads - in C# it would be the from ... select ...
stuff LINQ came with and in Haskell it would be do ...
blocks)
so assuming brick.ConnectAsync()
will return indeed some Async<...>
then you can wait for it using Async.RunSynchronously
like this:
let brick = Brick(BluetoothCommunication("COM3"))
let result = brick.ConnectAsync() |> RunSynchronously
sadly a quick browser search on the page you linked did not find ConnectAsync
so I cannot tell you exactly what the indent of the snippet was here but most likely you wanted to have this inside a async { ... }
block like this:
let myAsyncComputation =
async {
let brick = Brick(BluetoothCommunication "COM3")
let! result = brick.ConnectAsync()
// do something with result ...
}
(note that I remove some unnecessary parentheses etc.)
and then you could use this myAsyncComputation
async { .. }
workflowAsync.RunSynchronously
to run and await itAsync.Start
to run it in background (your block needs to have type Async<unit>
for thisAsync.StartAsTask
to start and get a Task<...>
out of itIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With