r-lib / coro

Coroutines for R
https://coro.r-lib.org/
Other
160 stars 8 forks source link

Access value of promise from async() function #61

Open JosiahParry opened 1 day ago

JosiahParry commented 1 day ago

Using a modified example from {coro}, it is unclear how to access the value of the function. Here we return n after the async function has completed.

async_count_down <- coro::async(function(n) {
  while (n > 0) {
    cat("Down", n, "\n")
    coro::await(coro::async_sleep(1))
    n <- n - 1
  }
  n
})

n <- async_count_down()

Running this results in a promise (expected) however, trying to get the value via n$finally() results in an error.

At present it seems that using async() is intended only for functions with side effects. Is that correct?

lionel- commented 19 hours ago

coro::async() inherits the properties of promises (https://rstudio.github.io/promises). By default they are scheduled by a top-level event loop that runs when R is idle so only that loop and the tasks it manages (promises including ones created by async functions) have access to values.

In practice this means you can only access values from an async function only from another async context by using await().

I think there are ways to create local event loops that allow you to block on a promise (like block_on() in Rust) but I haven't tried this: https://github.com/r-lib/later/blob/82d9609217fdddb601b1569891f9fcece62a78be/R/later.R#L28