Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

construct only be used within computation expressions

Tags:

f#

I'v an async function that returns a string asynchronously and I'm calling that function within test method and is throwing computation expressions, what would be the possible fix?

Code

let requestDataAsync (param: string) : Async<string> = 
    async {
        Console.WriteLine param
        return "my result"
    }

Test Code

[<TestMethod>]
member this.TestRequestDataAsync() =
    let! result = requestDataAsync("some parameter")

    Console.WriteLine(result)
    Assert.IsTrue(true)

Error for this line let! result = requestDataAsync("some parameter")

This construct can only be used within computation expressions

Question, How to wait and display the result of the async function?

like image 632
App2015 Avatar asked Dec 24 '22 08:12

App2015


2 Answers

Calls to let! must appear at the top level of the computation expression. You can fix it by creating a nested async { } block:

[<TestMethod>]
member this.TestRequestDataAsync() =
async 
{      
    let! result = requestDataAsync("some parameter")
    Console.WriteLine(result)
    Assert.IsTrue(true)
 }
like image 182
Kevin Avignon Avatar answered Feb 14 '23 04:02

Kevin Avignon


The answer would be to use RunSynchronously. that way you can wait on the function call.

let result = "some parameter" |> requestMetadataAsync |> Async.RunSynchronously
like image 41
App2015 Avatar answered Feb 14 '23 04:02

App2015