0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It might be best not to encourage the use of this without making it clear that it's a last resort and should be quite rare in production code.
Fair enough. Added a section.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.