How to actually invoke promises?

143 views Asked by At

I was looking at the promises package, but I can't figure out how to actually get promises do anything. All the available blocking mechanisms (like promise_all) return a promise, and there seems to be no obvious way to have the promise execute in the first place. For example, given the following code snippet:

library(promises)

p <- promise(~ {
  print("executing promise")
}) %>% then(~ {
  print("promise is done")
})

print("we are here")

done <- FALSE
all_promises <- promise_all(p) %>% then(~ {
  print("all promises done")
  done <<- TRUE
})

# output:
# [1] "executing promise"
# [1] "we are here"

how do I actually invoke the promise chain?

Weirdly enough, if I change the first promise to a future_promise and add a run loop as in

while(!done) {
  later::run_now()
  Sys.sleep(0.01)
}

the promise chain executes correctly. This doesn't work with a regular promise though.

What am I missing? It seems that the system is lacking an executor, but where do I get an executor? I don't see any in the package itself, and there is no user-visible API for querying promises that I can see.

1

There are 1 answers

3
MrMobster On

It turns out I was using the API incorrectly. A promise expression is supposed to call the continuation callback. I missed that detail. So this works:

library(promises)

p <- promise(~ {
  print("executing promise")
  resolve(1)
}) %>% then(~ {
  print("promise is done")
})

print("we are here")

done <- FALSE
all_promises <- promise_all(p) %>% then(~ {
  print("all promises done")
  done <<- TRUE
})

while(!done) {
  later::run_now()
  Sys.sleep(0.1)
}