Dipanshu Verma
Dipanshu Verma

Reputation: 101

Get result from Async Result object in F#

I have a piece of code that is of the following form

let function arg1 arg2 =
  match arg1 with
  | type1 -> Some true
  | type2 -> 
      async {
        match! func2 arg3 arg4 with
        | Result.Ok a -> return! Some true
        | _ -> return! None
      }

The problem here is that the func2 has to be used with match! statement and a normal match keyword is not able to compute the expression and thus I can not match pattern Some a. However, I can not use async in one of the branches alone.

Is there any method in F# that can convert Async<Result<a>> to Result<a> type ?

I am expecting a method such as Async.Evaluate that can perform computation and return a simple Result<a> object instead of a Async<Result<a>>. that would my code snippet look something like:

let function arg1 arg2 =
  match arg1 with
  | type1 -> Some true
  | type2 -> 
      match (func2 arg3 arg4) |> Async.Evaluate with
      | Result.Ok a -> Some true
      | _ -> None

Upvotes: 0

Views: 162

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80724

The function you're looking for is Async.RunSynchronously

    match (func2 arg3 arg4) |> Async.RunSynchronously with
      | Result.Ok a -> Some true
      | _ -> None

Note, however, that, as a rule, a call to RunSynchronously should not appear anywhere in your code, except the entry point. Or maybe event handler, if you're working with a UI framework of some kind.

A better solution is to make the calling function also async:

let function arg1 arg2 =
  match arg1 with
  | type1 -> async { return Some true }
  | type2 -> 
      async {
        match! func2 arg3 arg4 with
        | Result.Ok a -> return Some true
        | _ -> return None
      }

And then making the function calling it also async, and the one calling it, and the one calling it, and so on, all the way to the entry point, which would finally call RunSynchronously, or maybe even Async.Start, depending on your needs.

Upvotes: 1

Related Questions