async {coro}R Documentation

Make an async function

Description

async() functions are building blocks for cooperative concurrency.

The async framework used by async() functions is implemented in the later and promises packages:

Usage

async(fn)

await(x)

Arguments

fn

An anonymous function within which await() calls are allowed.

x

An awaitable value, i.e. a promise.

Value

A function that returns a promises::promise().

See Also

async_generator() and await_each(); coro_debug() for step-debugging.

Examples

# This async function counts down from `n`, sleeping for 2 seconds
# at each iteration:
async_count_down <- async(function(n) {
  while (n > 0) {
    cat("Down", n, "\n")
    await(async_sleep(2))
    n <- n - 1
  }
})

# This async function counts up until `stop`, sleeping for 0.5
# seconds at each iteration:
async_count_up <- async(function(stop) {
  n <- 1
  while (n <= stop) {
    cat("Up", n, "\n")
    await(async_sleep(0.5))
    n <- n + 1
  }
})

# You can run these functions concurrently using `promise_all()`
if (interactive()) {
  promises::promise_all(async_count_down(5), async_count_up(5))
}

[Package coro version 1.0.4 Index]