Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I await an async method in F#

Tags:

async-await

f#

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.

like image 221
Scott Nimrod Avatar asked Feb 20 '16 11:02

Scott Nimrod


People also ask

Can you await an async function?

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.

How do I add async await to function?

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.

What does the async keyword in async function f () mean?

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.

How do you wait for an async function to finish?

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.


1 Answers

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

  • inside yet another async { .. } workflow
  • with Async.RunSynchronously to run and await it
  • with Async.Start to run it in background (your block needs to have type Async<unit> for this
  • with Async.StartAsTask to start and get a Task<...> out of it
  • ...
like image 183
Random Dev Avatar answered Oct 06 '22 13:10

Random Dev