How to unbox Async<string> []

101 views Asked by At

So I have an Async<string> [] and for the life of me I can't figure out how to unbox it!

I started with

Job<Result<string>> []

Then I managed to get it to

Job<string> []

So I added in Job.toAsync thinking converting it to an async might be easier to get out. NOPE

Now I have

Async<string> []

I'm using the Hopac lib

So my question is, how do I just get a string []

1

There are 1 answers

0
Fyodor Soikin On BEST ANSWER

You need to somehow run those asyncs, so that each returns you a value. The easiest way is to run them in parallel, for there is a built-in function for it - Async.Parallel. This function takes a sequence of asyncs and returns an async of an array, which you can then run with Async.RunSynchronously or similar:

let asyncs : Async<string> [] = ...
let results = asyncs |> Async.Parallel |> Async.RunSynchronously

Alternatively, if you want them to run sequentially, you could run them one by one and accumulate the result as you go. Unfortunately, there is no built-in function to do it, so you'll have to code it yourself. Something like this:

let runEm asyncs =
   let loop rest resultsSoFar = 
      match rest with
      | x::xs -> 
          async {
             let! r = x
             return! loop xs (r:resultsSoFar)
          }
      | [] -> 
          async { return resultsSoFar }

   async {
     let! ress = loop asyncs [] 
     return ress |> List.reverse
   }

// Usage:
let asyncs : Async<string> [] = ...
let results = runEm asyncs |> Async.RunSynchronously