Skip to content

Instantly share code, notes, and snippets.

@wch
Last active March 7, 2019 16:53
Show Gist options
  • Save wch/7e55d4b9a8f2d640c8d66ca166858b6d to your computer and use it in GitHub Desktop.
Save wch/7e55d4b9a8f2d640c8d66ca166858b6d to your computer and use it in GitHub Desktop.
Promise chains and interrupts
library(promises)
library(later)
# Regular version ===========
# Interrupts during execution of a step in the promise chain cause the chain to stop
# without running further steps, the catch, or finally.
# Ideally, the finally would run, but not the others.
{
p <- promise_resolve(TRUE)
p <- p$then(function(value) {
message("step 2")
Sys.sleep(5)
})
p <- p$then(function(value) {
message("done")
})
p <- p$catch(function(err) {
message("Caught error")
})
p_is_finished <- FALSE
p <- p$finally(function() {
message("finally")
p_is_finished <<- TRUE
})
while (!p_is_finished) {
run_now()
}
# Press Esc/Ctrl-C when it's in step 2
# The catch and the finally do not execute
}
# trycatch version ===========
# This is a modified version of the previous example, with tryCatch.
# The catch and the finally both execute, although we want to have only
# the finally execute.
{
p <- promise_resolve(TRUE)
p <- p$then(function(value) {
tryCatch({
message("step 2")
Sys.sleep(4)
},
interrupt = function(e) stop("interrupted")
)
})
p <- p$then(function(value) {
message("done")
})
p <- p$catch(function(err) {
message("Caught error: ", err)
})
p_is_finished <- FALSE
p <- p$finally(function() {
message("finally")
p_is_finished <<- TRUE
})
while (!p_is_finished) {
run_now()
}
# Press Esc/Ctrl-C when it's in step 2
# The catch and the finally both execute
}
# Interrupts while waiting for a timeout ==============
# In this example, the interrupt happens when the promise code is not executing.
# The done and finally execute, but only after control returns to the console and
# later is running the event loop in the background via R's input handler.
{
p <- promise(function(resolve, reject) {
message("step 1")
later(function() resolve(TRUE), 4)
})
p <- p$then(function(value) {
message("done")
})
p <- p$catch(function(err) {
message("Caught error: ", err)
})
p_is_finished <- FALSE
p <- p$finally(function() {
message("finally")
p_is_finished <<- TRUE
})
while (!p_is_finished) {
run_now()
}
# Press Esc/Ctrl-C when it's in step 2
# The done and finally will execute after exiting
}
# Note: Wrapping this examples in with_private_loop() would show more clearly that
# the done and finally are executed by the input handler.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment