promise: Create a new promise object

Description Usage Arguments Details Value Examples

View source: R/promise.R

Description

promise() creates a new promise. A promise is a placeholder object for the eventual result (or error) of an asynchronous operation. This function is not generally needed to carry out asynchronous programming tasks; instead, it is intended to be used mostly by package authors who want to write asynchronous functions that return promises.

Usage

1
promise(action)

Arguments

action

A function with signature function(resolve, reject), or a one-sided formula. See Details.

Details

The action function should be a piece of code that returns quickly, but initiates a potentially long-running, asynchronous task. If/when the task successfully completes, call resolve(value) where value is the result of the computation (like the return value). If the task fails, call reject(reason), where reason is either an error object, or a character string.

It's important that asynchronous tasks kicked off from action be coded very carefully–in particular, all errors must be caught and passed to reject(). Failure to do so will cause those errors to be lost, at best; and the caller of the asynchronous task will never receive a response (the asynchronous equivalent of a function call that never returns, i.e. hangs).

The return value of action will be ignored.

Value

A promise object (see then).

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Create a promise that resolves to a random value after 2 secs
p1 <- promise(function(resolve, reject) {
  later::later(~resolve(runif(1)), delay = 2)
})

p1 %...>% print()

# Create a promise that errors immediately
p2 <- promise(~{
  reject("An error has occurred")
})
then(p2,
  onFulfilled = ~message("Success"),
  onRejected = ~message("Failure")
)

promises documentation built on July 1, 2020, 10:26 p.m.