Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access value of promise from async() function #61

Open
JosiahParry opened this issue Dec 2, 2024 · 1 comment
Open

Access value of promise from async() function #61

JosiahParry opened this issue Dec 2, 2024 · 1 comment

Comments

@JosiahParry
Copy link

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-
Copy link
Member

lionel- commented Dec 3, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants