|
| 1 | +## ParallelAsyncResult Computation Expression |
| 2 | + |
| 3 | +Namespace: `FsToolkit.ErrorHandling` |
| 4 | + |
| 5 | +This CE operates on the same type as `asyncResult`, but it adds the `and!` operator for running workflows in parallel. |
| 6 | + |
| 7 | +Concurrent workflows are run with the same semantics as [`Async.Parallel`](https://fsharp.github.io/fsharp-core-docs/reference/fsharp-control-fsharpasync.html#Parallel), so only the first exception is returned. |
| 8 | + |
| 9 | + |
| 10 | +## Examples |
| 11 | + |
| 12 | +### Example 1 |
| 13 | + |
| 14 | +Suppose we want to download 3 files. |
| 15 | + |
| 16 | +Here is our simulated download function: |
| 17 | + |
| 18 | +```fsharp |
| 19 | +// string -> Async<Result<string, string>> |
| 20 | +let downloadAsync stuff : Async<Result<string, string>> = async { |
| 21 | + do! Async.Sleep 3_000 |
| 22 | + return Ok stuff |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +This workflow will download each item in sequence: |
| 27 | + |
| 28 | +```fsharp |
| 29 | +let downloadAllSequential = ayncResult { |
| 30 | + let! x = downloadAsync (Ok "We") |
| 31 | + let! y = downloadAsync (Ok "run") |
| 32 | + let! z = downloadAsync (Ok "sequentially :(") |
| 33 | + return sprintf "%s %s %s" x y z |
| 34 | +} |
| 35 | +``` |
| 36 | + |
| 37 | +It takes 9 seconds to complete. |
| 38 | + |
| 39 | +However, using `parallelAsyncResult`, we can download all 3 concurrently: |
| 40 | + |
| 41 | +```fsharp |
| 42 | +// Async<Result<string, string>> |
| 43 | +let downloadAll = parallelAsyncResult { |
| 44 | + let! x = downloadAsync (Ok "We") |
| 45 | + and! y = downloadAsync (Ok "run") |
| 46 | + and! z = downloadAsync (Ok "concurrently!") |
| 47 | + return sprintf "%s %s %s" x y z |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +This takes just 3 seconds. |
0 commit comments