rstudio / promises

A promise library for R
https://rstudio.github.io/promises
Other
201 stars 19 forks source link

Docs should explain why function passed to promise() is run immediately #7

Open wch opened 6 years ago

wch commented 6 years ago

This follows a brief discussion that @jcheng5 and I had on the topic.

The following prints 0, 1, 2, 3, 4, which was surprising to me -- I expected 0, 3, 1, 2, 4.

library(promises)
f <- function() {
  cat("0\n", file=stderr())

  p <- promise(function(resolve, reject) {
    cat("1\n", file=stderr())
    resolve("Hi")
    cat("2\n", file=stderr())
  })

  cat("3\n", file=stderr())

  then(p, function(value) {
    cat("4\n", file=stderr())
  })
}

f()

It would help if ?promise explained that the function runs immediately, and why it does so. Otherwise, I have a feeling that many developers would put their slow code in promise() call, which sort of defeats the purpose of using promises.


Promises in Javascript work the same way, which surprised me again:

function f() {
  console.log(0)

  let p = new Promise((resolve, reject) => {
    console.log(1)
    resolve("Hi")
    console.log(2)
  });

  console.log(3)

  p.then((successMessage) => {
    console.log("4");
  });
}

f()

This answer on SO explains why JS promises work that way (though it's still not entirely clear in my mind): https://stackoverflow.com/a/31324439/412655