How to make two Async <> calls with different types of results in parallel?

I have two asynchronous operations, so I have the following functions:

 // Returs Async<Person> let GetPerson = ... // Returs Async<Address> let GetAddress = ... 

What is the idiomatic way of doing them in parallel and getting their results?

My starting point is this approach.

 let MyFunc = async { let! person = GetPerson() let! address = GetAddress() ... } 

This works, but it performs two operations in sequence.

I also tried this (sort of like in my C # experience).

 let MyFunc = async { let personA = GetPerson() let addressA = GetAddress() let! person = personA let! address = addressA ... } 

But it does not work, it also performs two operations in sequence.

Most documentation descriptions use Async.Parallel with a sequence, but the problem is that the type of the result of the two operations is different, so I cannot put them in a sequence.

 let MyFunc = async { let personA = GetPerson() let addressA = GetAddress() [personA; addressA] |> Async.Parallel ... } 

This gives a compilation error because the two values ​​are of different types. (And also, with this syntax, how can I get the actual results?)

What is an idiomatic way to do this?

+5
source share
1 answer

The idiomatic approach is to start both calculations with Async.StartAsChild , and then wait for them to complete using the second let! :

 let MyFunc = async { let! personWork = GetPerson() |> Async.StartChild let! addressWork = GetAddress() |> Async.StartChild let! person = personWork let! address = addressWork // (...) } 

Just calling GetPerson does not actually start the job - unlike C #, where tasks are started, F # workflows are just descriptions of the work being done, so you need to run them explicitly. The Async.StartChild operation gives you a workflow that starts work and returns another workflow that you can use to wait for it to complete.

+8
source

Source: https://habr.com/ru/post/1262051/


All Articles