Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the result of Async Tasks in F#

Tags:

f#

I am trying to get the result of this statement and use it in the next statement but I think I don't quite get the asynchronous nature of it. orders is a collection of records and I am trying to get the order details but I end up with a type seq<Threading.Tasks.Task> and not sure how to get a collection of the results. In nodejs I would use an async function and await orders... ( etc )

let fullOrders = 
    orders.AsParallel().WithDegreeOfParallelism(6) |>
    Seq.map (fun (order) -> getOrderInfoApi(client1, order.increment_id ))
like image 773
Martin Thompson Avatar asked Nov 24 '25 19:11

Martin Thompson


1 Answers

I assume that you get a collection of tasks as a result because getOrderInfoApi returns a Task.

First of all, I think you are trying to mix two different things. The ParallelQuery API that you use through AsParallel is useful when you want to parallelize some data processing where the individual steps are synchronous (e.g. calculation). However, you also use Task in getOrderInfoApi to make that asynchronous, which is another kind of concurrency. You really only need to use one of these. If getOrderInfoApi is already asynchronous, the question is how to run all those returned tasks in parallel.

You can do this by using Task.WhenAll. This gives you a task that will return all results when it completes. You can wait for this synchronously, or use it in some other asynchronous context (depending on the kind of application you're building):

let tasks = 
  orders 
  |> Seq.map (fun (order) -> getOrderInfoApi(client1, order.increment_id ))
  |> Task.WhenAll

// This will block the current thread until all `getOrderInfoApi` complete
let res = tasks.Result

That said, if you are new to F# and you are not sure about what asynchronous programming abstraction is best for you, then I would recommend looking into F# asynchronous workflows instead of tasks.

like image 170
Tomas Petricek Avatar answered Nov 27 '25 19:11

Tomas Petricek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!