August 1, 2025
⏳📩🔄
📨
→ mirai()
runs R code in the background, without blocking the R session.
How to check for a result?
How to check for a result?
→ Like checking email every 15 mins.
background thread
$data
or unresolved()
main thread
→ Much more asynchronous.
→ Efficient by doing as much as possible early.
→ So, not quite like checking for email.
Use []
to wait for and collect the result:
→ This is efficient, but blocking.
https://rstudio.github.io/promises/
Higher level - interface for async
as.promise(x)$then(func)
Lower level - implementation for async
later(func, secs)
as.promise.mirai <- function(x) {
promises::promise(
function(resolve, reject) {
check <- function() {
if (unresolved(x)) {
later::later(check, delay = 0.1)
} else {
value <- x$data
if (is_error_value(value)) reject(value) else resolve(value)
}
}
check()
}
)
}
→ Schedules itself to check every 0.1 secs via later.
as.promise.mirai <- function(x) {
promises::promise(
function(resolve, reject) {
if (unresolved(x)) {
.keep(x, environment())
} else {
value <- x$data
if (is_error_value(value)) reject(value) else resolve(value)
}
}
)
}
→ No repeating check.
→ .keep()
is a special function which tells the mirai completion callback to call into later (via its C interface) to resolve the promise.
→ Actions are scheduled as soon as a mirai completes.
See these slides at https://shikokuchuo.net/user2025