1

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
MrMobster
  • 1,851
  • 16
  • 25

1 Answers1

2

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)
}
MrMobster
  • 1,851
  • 16
  • 25
  • The `promise_all` call in your code doesn’t do anything, does it? You’ve only got a single promise anyway. No need to wrap it. And don’t feel bad for using the API incorrectly … after all, this is documented *nowhere*. It’s actually a weird oversight in the documentation. – Konrad Rudolph Jul 01 '21 at 13:25
  • 1
    I seem to be blind. It *is* documented, right in the middle of the [`promise`](https://rstudio.github.io/promises/reference/promise.html) article, where it belongs. Merely the introductory articles don’t mention it, which is still a bit odd. – Konrad Rudolph Jul 01 '21 at 13:36
  • @KonradRudolph yeah, the same thing happened to me. It's right in there, but it's not obvious unless one really *reads* the documentation (and who does that anyway, right?). As to all_promises()... I just left it in there as an example of promise collection. You are right that it does nothing in this particular code. – MrMobster Jul 01 '21 at 14:04