App2015
App2015

Reputation: 993

construct only be used within computation expressions

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?

Upvotes: 4

Views: 582

Answers (2)

App2015
App2015

Reputation: 993

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

let result = "some parameter" |> requestMetadataAsync |> Async.RunSynchronously

Upvotes: 5

Kevin Avignon
Kevin Avignon

Reputation: 2903

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)
 }

Upvotes: 5

Related Questions