Debian Codegraph @

R/then.R

raw
1 #' Access the results of a promise
2 #'
3 #' Use the `then` function to access the eventual result of a promise (or, if
4 #' the operation fails, the reason for that failure). Regardless of the state of
5 #' the promise, the call to `then` is non-blocking, that is, it returns
6 #' immediately; so what it does *not* do is immediately return the result value
7 #' of the promise. Instead, you pass logic you want to execute to `then`, in the
8 #' form of function callbacks. If you provide an
9 #' `onFulfilled` callback, it will be called upon the promise's successful
10 #' resolution, with a single argument `value`: the result value. If you provide
11 #' an `onRejected` callback, it will be called if the operation fails, with a
12 #' single argument `reason`: the error that caused the failure.
13 #'
14 #' @section Formulas:
15 #'
16 #' `r lifecycle::badge("superseded")`
17 #'
18 #' With `{promises}` depending on R >= 4.1, the shorthand of a formula, `~
19 #' fn(.)` is no longer recommended by the `{promises}` package or tidyverse (for
20 #' example,
21 #' [`{purrr}`](https://github.com/tidyverse/purrr/commit/670c3ed9920f15da0d4175068ecddc41f0f1f335#diff-c4dcc43795da5c7f6bf5a94d957b5507ce795fedd6d3eb092ccad03678c4f76dR15))
22 #' as we now have access to the function shorthand, `\(x) fn(x)`. Please update
23 #' your code to use the new function shorthand syntax `\(x) fn(x, arg1, args2)`
24 #' instead of `~ fn(., arg1, arg2)`. The `.` can be confusing when chained with
25 #' other methods.
26 #'
27 #' @section Chaining promises:
28 #'
29 #' The first parameter of `then` is a promise; given the stated purpose of the
30 #' function, this should be no surprise. However, what may be surprising is that
31 #' the return value of `then` is also a (newly created) promise. This new
32 #' promise waits for the original promise to be fulfilled or rejected, and for
33 #' `onFulfilled` or `onRejected` to be called. The result of (or error raised
34 #' by) calling `onFulfilled`/`onRejected` will be used to fulfill (reject) the
35 #' new promise.
36 #'
37 #' ```r
38 #' promise_a <- get_data_frame_async()
39 #' promise_b <- then(promise_a, onFulfilled = head)
40 #' ```
41 #'
42 #' In this example, assuming `get_data_frame_async` returns a promise that
43 #' eventually resolves to a data frame, `promise_b` will eventually resolve to
44 #' the first 10 or fewer rows of that data frame.
45 #'
46 #' Note that the new promise is considered fulfilled or rejected based on
47 #' whether `onFulfilled`/`onRejected` returns a value or throws an error, not on
48 #' whether the original promise was fulfilled or rejected. In other words, it's
49 #' possible to turn failure to success and success to failure. Consider this
50 #' example, where we expect `some_async_operation` to fail, and want to consider
51 #' it an error if it doesn't:
52 #'
53 #' ```r
54 #' promise_c <- some_async_operation()
55 #' promise_d <- then(promise_c,
56 #' onFulfilled = function(value) {
57 #' stop("That's strange, the operation didn't fail!")
58 #' },
59 #' onRejected = function(reason) {
60 #' # Great, the operation failed as expected
61 #' NULL
62 #' }
63 #' )
64 #' ```
65 #'
66 #' Now, `promise_d` will be rejected if `promise_c` is fulfilled, and vice
67 #' versa.
68 #'
69 #' **Warning:** Be very careful not to accidentally turn failure into success,
70 #' if your error handling code is not the last item in a chain!
71 #'
72 #' ```r
73 #' some_async_operation() |>
74 #' catch(function(reason) {
75 #' warning("An error occurred: ", reason)
76 #' }) |>
77 #' then(function() {
78 #' message("I guess we succeeded...?") # No!
79 #' })
80 #' ```
81 #'
82 #' In this example, the `catch` callback does not itself throw an error, so the
83 #' subsequent `then` call will consider its promise fulfilled!
84 #'
85 #' @section Convenience functions:
86 #'
87 #' For readability and convenience, we provide `catch` and `finally` functions.
88 #'
89 #' The `catch` function is equivalent to `then`, but without the `onFulfilled`
90 #' argument. It is typically used at the end of a promise chain to perform error
91 #' handling/logging.
92 #'
93 #' The `finally` function is similar to `then`, but takes a single no-argument
94 #' function that will be executed upon completion of the promise,
95 #' regardless of whether the result is success or failure. It is typically used
96 #' at the end of a promise chain to perform cleanup tasks, like closing file
97 #' handles or database connections. Unlike `then` and `catch`, the return value
98 #' of `finally` is ignored; however, if an error is thrown in `finally`, that
99 #' error will be propagated forward into the returned promise.
100 #'
101 #' @section Visibility:
102 #'
103 #' `onFulfilled` functions can optionally have a second parameter `visible`,
104 #' which will be `FALSE` if the result value is [invisible][base::invisible()].
105 #'
106 #' @param promise A promise object. The object can be in any state.
107 #' @param onFulfilled A function that will be invoked if the promise value
108 #' successfully resolves. When invoked, the function will be called with a
109 #' single argument: the resolved value. Optionally, the function can take a
110 #' second parameter `.visible` if you care whether the promise was resolved
111 #' with a visible or invisible value. The function can return a value or a
112 #' promise object, or can throw an error; these will affect the resolution of
113 #' the promise object that is returned by `then()`.
114 #' @param onRejected A function taking the argument `error`. The function can
115 #' return a value or a promise object, or can throw an error. If `onRejected`
116 #' is provided and doesn't throw an error (or return a promise that fails)
117 #' then this is the async equivalent of catching an error.
118 #' @param ... Ignored.
119 #' @param tee If `TRUE`, ignore the return value of the callback, and use the
120 #' original value instead. This is useful for performing operations with
121 #' side-effects, particularly logging to the console or a file. If the
122 #' callback itself throws an error, and `tee` is `TRUE`, that error will still
123 #' be used to fulfill the the returned promise (in other words, `tee` only has
124 #' an effect if the callback does not throw).
125 #' @export
126 then <- function(
127 promise,
128 onFulfilled = NULL,
129 onRejected = NULL,
130 ...,
131 tee = FALSE
132 ) {
133 check_dots(...)
134 check_tee(tee)
135
136 promise <- as.promise(promise)
137
138 if (!is.null(onFulfilled) && !is.function(onFulfilled)) {
139 onFulfilled <- rlang::as_function(onFulfilled)
140 }
141 if (!is.null(onRejected) && !is.function(onRejected)) {
142 onRejected <- rlang::as_function(onRejected)
143 }
144 then_prom <-
145 if (!tee) {
146 promise$then(onFulfilled = onFulfilled, onRejected = onRejected)
147 } else {
148 # tee == TRUE
149
150 # Must normalize the callbacks to ensure they accept their arguments
151
152 onFulfilledTee <- NULL
153 if (!is.null(onFulfilled)) {
154 onFulfilled <- normalizeOnFulfilled(onFulfilled)
155 onFulfilledTee <- function(value, .visible) {
156 onFulfilled(value, .visible)
157 if (.visible) value else invisible(value)
158 }
159 }
160
161 onRejectedTee <- NULL
162 if (!is.null(onRejected)) {
163 onRejected <- normalizeOnRejected(onRejected)
164 onRejectedTee <- function(reason) {
165 onRejected(reason)
166 stop(reason) # Re-throw the error to propagate it
167 }
168 }
169
170 promise$then(
171 onFulfilled = onFulfilledTee,
172 onRejected = onRejectedTee
173 )
174 }
175 invisible(then_prom)
176 }
177
178 #' @rdname then
179 #' @export
180 catch <- function(promise, onRejected, ..., tee = FALSE) {
181 check_dots(...)
182 check_tee(tee)
183
184 promise <- as.promise(promise)
185
186 if (!is.null(onRejected) && !is.function(onRejected)) {
187 onRejected <- rlang::as_function(onRejected)
188 }
189
190 if (!tee) {
191 promise$catch(onRejected)
192 } else {
193 onRejected <- normalizeOnRejected(onRejected)
194 promise$catch(function(reason) {
195 onRejected(reason)
196 stop(reason)
197 })
198 }
199 }
200
201 #' @param onFinally A function with no arguments, to be called when the async
202 #' operation either succeeds or fails. Usually used for freeing resources that
203 #' were used during async operations.
204 #' @rdname then
205 #' @export
206 finally <- function(promise, onFinally) {
207 promise <- as.promise(promise)
208
209 if (!is.null(onFinally) && !is.function(onFinally)) {
210 onFinally <- rlang::as_function(onFinally)
211 }
212 promise$finally(onFinally)
213 }
214
215 check_dots <- function(..., call = parent.frame()) {
216 if (nargs()) {
217 rlang::check_dots_empty(call = call)
218 }
219 }
220
221 check_tee <- function(tee) {
222 if (is.logical(tee)) {
223 return()
224 }
225
226 rlang::abort(
227 "`tee` must be `TRUE` or `FALSE`",
228 call = parent.frame()
229 )
230 }