Debian Codegraph @

inst/doc/promises_07_combining.Rmd

raw
1 ---
2 title: "Combining promises"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteEngine{knitr::rmarkdown}
6 %\VignetteIndexEntry{Combining promises}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 So far, all of our examples have involved chaining operations onto a single promise. In practice, you'll often find yourself needing to perform tasks that require the results of more than one promise. These are some patterns you may find useful:
11
12 * [**Gathering:**](#gathering) Combining multiple independent promises into a single computation
13 * [**Nesting:**](#nesting) Using the result of one promise to affect the input or execution of another async operation
14 * [**Racing:**](#racing) Using the fastest of multiple promises
15 * [**Mapping:**](#mapping) Applying an async function to each of a list's elements and collecting the results
16 * [**Reducing:**](#reducing) Applying an async function to each of a list's elements and reducing
17
18 ## Gathering
19
20 The most common pattern for combining promises is gathering, where you have two or more promises in hand and you want to use all of their results in a computation. The `promise_all` function is designed for this. Its signature looks like:
21
22 ```r
23 promise_all(..., .list = NULL)
24 ```
25
26 `promise_all` takes any number of promises as named arguments, and returns a promise of a list containing named elements with the results of those promises.
27
28 Here's an example using `promise_all` to combine the results of two async `read.csv` operations:
29
30 ```r
31 library(promises)
32 library(mirai)
33
34 a <- mirai(read.csv("a.csv"))
35 b <- mirai(read.csv("b.csv"))
36
37 result <- promise_all(a = a, b = b) |>
38 then(\(values) {
39 rbind(values$a, values$b)
40 })
41 ```
42
43 In this example, the value of `values` within the curly braces is a list whose elements `a` and `b` are both data frames. We use `rbind` to combine them.
44
45 The `values$` prefix is a bit inelegant, so we recommend the use of the base R function `with`, which lets you skip the prefix. Here's the same example, with `with`:
46
47 ```r
48 library(promises)
49 library(mirai)
50
51 a <- mirai(read.csv("a.csv"))
52 b <- mirai(read.csv("b.csv"))
53
54 promise_all(a = a, b = b) |>
55 then(\(values) {
56 with(values, {
57 rbind(a, b)
58 })
59 })
60 ```
61
62 (Note that since the `promise_all` argument names are the same as the variable names (`a = a`, `b = b`), the original variables are masked: inside the `with` block, `a` now refers to the *result* of the promise `a`, not the promise object itself. If you find this confusing, you can just choose a different argument name, like `promise_all(a_result = a, …)`.)
63
64 The combination of `promise_all` and `with` is a concise and powerful way to gather the results of multiple promises.
65
66 `promise_all` also gives you two other options for passing input promises. First, if you would rather your result list be unnamed, you can pass in promises as unnamed arguments: `promise_all(a, b)` would yield `list(1, 2)`. Second, if you have a list of promises already in hand, you can pass the list as a single argument using `promise_all(.list = x)`(instead of, say, using `do.call(promise_all, x)`).
67
68 ```r
69 proms <-
70 lapply(c(a = "a.csv", b = "b.csv"), \(file) {
71 mirai(read.csv(file))
72 })
73 promise_all(.list = proms) |>
74 then(\(values) {
75 # values is a named list with elements a and b
76 with(values, {
77 rbind(a, b)
78 })
79 })
80 ```
81
82 ## Nesting
83
84 Gathering is easy and convenient, but sometimes not flexible enough. For example, if you use the result of promise `a` to decide whether to launch a second async task, whose result you then use in combination with the result of `a`.
85
86 ```r
87 library(promises)
88 library(mirai)
89
90 a <- mirai(1)
91
92 a |>
93 then(\(a) {
94 b <- mirai(2)
95 b |> then(\(b) a + b)
96 })
97 ```
98
99 (We use anonymous functions here to mask the names of the original promises--i.e. once inside the first anonymous function, the symbol `a` now refers to the result of the promise `a`.)
100
101 The nesting pattern is effective and flexible. The main downside is the physical nesting of the source code; if you use this pattern to a depth of more than a couple of promises, your code will be quite indented (in programming jargon this is referred to as the "pyramid of doom").
102
103 ## Racing
104
105 ```r
106 library(promises)
107 library(mirai)
108
109 a <- mirai({ Sys.sleep(1); 1 })
110 b <- mirai({ Sys.sleep(0.5); 2 })
111
112 first <- promise_race(a, b)
113 ```
114
115 `promise_race` takes multiple promises and returns a new promise that will be fulfilled with the first promise that succeeds. In the example above, `first` is a promise that will be fulfilled with `2` after 0.5 seconds.
116
117 If one of the input promises rejects before any succeed, then the returned promise will be rejected.
118
119 Note that promises does not currently support cancellation. So losing promises will attempt to run to completion even after the race ends.
120
121 ## Mapping
122
123 Use `promise_map` to run an async operation on each element of a list or vector, and collect the results in a list. It's very similar to `lapply` or `purrr::map`, except that the function to apply can return a promise, and the return value is also a promise.
124
125 In the example below, we iterate over a named vector of package names. For each package name, we launch an async task to download the package's description file from CRAN pick out the last published date.
126
127 ```r
128 library(promises)
129 library(mirai)
130
131 get_pub_date <- \(pkg) {
132 desc_url <- paste0("https://cran.r-project.org/web/packages/", pkg, "/DESCRIPTION")
133 mirai(
134 {
135 r <- read.dcf(url(desc_url))[, "Date/Publication"]
136 unname(r)
137 },
138 desc_url = desc_url
139 )
140 }
141
142 packages <- setNames(, c("ggplot2", "dplyr", "knitr"))
143
144 pkg_dates <- promise_map(packages, get_pub_date)
145
146 pkg_dates |> then(print)
147 ```
148
149 The resulting output looks like this:
150
151 ```
152 $ggplot2
153 [1] "2025-04-09 09:40:10 UTC"
154
155 $dplyr
156 [1] "2023-11-17 16:50:02 UTC"
157
158 $knitr
159 [1] "2025-03-16 09:20:02 UTC"
160 ```
161
162 `promise_map` works serially; each time it calls the given function on an element of the list/vector, it will wait for the returned promise to resolve before proceeding to the next element. Furthermore, any error or rejected promise will cause the entire `promise_map` operation to reject.
163
164 If you want behavior that's similar to `promise_map` but for all the async operations to occur in parallel, you can achieve that with a combination of a regular `purrr::map` and `promise_all`:
165
166 ```r
167 pkg_dates <- purrr::map(packages, get_pub_date) |>
168 promise_all(.list = _)
169
170 pkg_dates |> then(print)
171 ```
172
173 ## Reducing
174
175 Use `promise_reduce` when you have a list where you want to run an async operation on each of the elements, and to do so serially (i.e. only one async operation runs at a time). This can be helpful when you're searching through some elements using an async operation and want to terminate early when your search succeeds.
176
177 The signature of `promise_reduce` is as follows:
178
179 ```r
180 promise_reduce(x, func, init = NULL)
181 ```
182
183 If you've worked with `base::Reduce()` or `purr:::reduce()`, this should seem reasonably familiar: `x` is a vector or list; `func` is a function that takes two arguments, the accumulated value and the "next" value; and `init` is the default accumulated value.
184
185 The main difference between `promise_reduce` and `purrr:::reduce` is that with `promise_reduce`, your `func` can return a promise. If it does, `promise_reduce` will wait for it to resolve before updating the accumulated value and invoking `func` on the next element. The result returned from `promise_reduce` is a promise that resolves to the ultimate accumulated value.
186
187 The following example loops through a partial list of CRAN mirrors, returning the first one that passes whatever check `http::http_error` performs.
188
189 ```r
190 library(promises)
191 library(mirai)
192
193 cran_mirrors <- c(
194 "https://cloud.r-project.org",
195 "https://cran.usthb.dz",
196 "https://cran.csiro.au",
197 "https://cran.wu.ac.at"
198 )
199
200 promise_reduce(
201 cran_mirrors,
202 \(result, mirror) {
203 if (!is.null(result)) {
204 result
205 } else {
206 mirai(
207 {
208 # Test the URL; return the URL on success, or NULL on failure
209 if (!httr::http_error(mirror)) mirror
210 },
211 mirror = mirror
212 )
213 }
214 },
215 .init = NULL
216 ) |>
217 then(print)
218 ```