Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export(promise_reduce)
export(promise_reject)
export(promise_resolve)
export(then)
export(wait_for)
export(with_ospan_async)
export(with_ospan_promise_domain)
export(with_promise_domain)
Expand Down
42 changes: 42 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,45 @@ function() {
is_false <- function(x) {
is.logical(x) && length(x) == 1L && !is.na(x) && !x
}

#' Wait for a Promise
#'
#' Synchronizes a promise by waiting for it to complete and then retrieving its
#' value.
#'
#' @inheritParams then
#' @param loop the \pkg{later} loop on which the promise has been scheduled.
#' Defaults to [later::current_loop()].
#'
#' @return The value of the resolved promise. An error will be thrown if the
#' promise is rejected.
#'
#' @examples
#' # Returns a promise for the sum of e1 + e2, with a 1 sec delay
#' slowly_add <- function(e1, e2) {
#' promise(\(resolve, reject) {
#' later::later(\() resolve(e1 + e2), delay = 1)
#' })
#' }
#'
#' # Returns 3 after 1 second
#' res <- wait_for(slowly_add(1, 2))
#' res
#'
#' @export
wait_for <- function(promise, loop = later::current_loop()) {
if (!is.promise(promise)) {
stop("wait_for() requires a promise object")
}
private <- attr(promise, "promise_impl")$.__enclos_env__$private
while (private$state == "pending") {
later::run_now(Inf, all = FALSE, loop = loop)
}
if (private$state == "rejected") {
stop(conditionMessage(private$value))
}
if (private$visible) {
return(private$value)
}
invisible(private$value)
}
35 changes: 35 additions & 0 deletions man/wait_for.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkgdown/_pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ reference:
contents:
- then
- hybrid_then
- wait_for
- pipes
- title: Combining promises
contents:
Expand Down