Live data from Hacker News

Callbacks are imperative, promises are functional

blog.jcoglan.com

81–90 of 154 posts

Re: Callbacks are imperative, promises are functional

#81

Ryan Dahl in February 2010, when Promises were removed from core: Because many people (myself included) only want a low-level interface to file system operations that does not necessitate creating an object, while many other people want something like promises but different in one way or another. So instead of promises we'll use last argument callbacks and consign the task of building better abstraction layers to use…

> There still isn't a canonical Promises specification.

Yes, there is: https://github.com/promises-aplus/promises-spec

Re: Callbacks are imperative, promises are functional

#82
Unfortunately, in practice promises end up making your code more difficult to reason about by adding cruft and unnecessary abstraction. They're also very limiting from a control-flow perspective.

This is especially noticeable when you have branching behavior / want to resolve a promise early[1]:

Branching with promises:

  function doTask(task, callback) {
    return Q.ncall(task.step1, task)
    .then(function(result1) {
      if (result1) {
        return result1;
      } else {
        return continueTasks(task);
      }
    })
    .nodeify(callback)
  }

  function continueTasks(task) {
    return Q.ncall(task.step2, task);
    .then(function(result2) {
      return Q.ncall(task.step3, task);
    })
  }
As opposed to with stepdown[2]:

  function doTask(task, callback) {
    $$([
      $$.stepCall(task.step1),
      function($, result1) {
        if (result1) return $.end(null, result1)
      },
      $$.stepCall(task.step2),
      $$.stepCall(task.step3)
    ], callback)
  }
I would really love for a post to include a non-trivial problem implemented with promises, vanilla callbacks, and async (and I'd be happy to add a stepdown equivalent), and allow people to see for themselves (how in my opinion promises make code harder to read).

[1] http://stackoverflow.com/questions/11302271/how-to-properly-...

[2] https://github.com/Schoonology/stepdown (docs need updating, view tests for documentation)

Re: Callbacks are imperative, promises are functional

#83
post #52

> If foo takes many arguments we add more arrows, i.e. foo :: a -> b -> c > means that foo takes two arguments of types a and b and returns something of > type c. Nitpick alert: since everything is curried in Haskell, it's actually more like `foo takes an argument a and returns a function that takes one b and returns one c`. Other than that teeny thing, this article is awesome, and I fully agree. Promises are an exce…

Really? Consider f :: a -> b -> a f a = g a g :: a -> b -> a g a _ = a It doesn't seem right to say that g "returns a function that takes one b", whereas you could say that about f.

(g a) is valid Haskell and it is equal to a constant function that returns a. In fact, g is the Prelude function 'const'.

Re: Callbacks are imperative, promises are functional

#84
post #73

Promises are just tools for managing a list of callbacks with less boilerplate. I wouldn't call one imperative and the other functional. Both are functional. You might dislike callback patterns, but through one of the beautiful parts of JS, you can trivially wrap any callback-oriented API you want and have it become a promise based one. I've done this before when I had a very complex dependency graph at the start of…

The author "promisify"s a callback-based API in the article - which is worth a read by the way. I'm interested in your opinion RE: his argument for why callback APIs are imperative - because I think he has a very good point and has supported it with a solid argument and you haven't offered any rebuttal.

Interesting. As you pointed out, I hadn't read the article but was rather replying to other comments.

After reading it, I think I have to agree that I had never thought about it that way. It makes a lot more sense that a promise is just a declaration of some unit of work, and when you can use a promise like any other data, you aren't just giving imperative commands, but rather describing work to be done and using that as a fundamental part of your code, which is why it drastically simplifies async programming (the relation of promises to monads is quite nice, too). Definitely a good article, thanks for kicking me :).

Re: Callbacks are imperative, promises are functional

#85
post #53

Earlier quoted context omitted.

Nope, the shared scope would obligate me to create a function with binded params for each iteration so "i" is not the last value (e.g. path.length) in every call. Examples: http://stackoverflow.com/questions/1451009/javascript-infamo...

Exactly, one of the advantages of using a good abstraction like forEach() is that it prevents you from making that kind of mistake. On the other hand, it can be more costly in cases where you don't need the closure. All abstractions by definition have some tradeoffs, some visible or hidden complexity, and some extra knowledge. Promises are no different.

I see no benefits in promises, zero, none.

Re: Callbacks are imperative, promises are functional

#86

This is an interesting perspective. But to me, even having spent a year on a large node.js project, I just don't see how promises would have simplified things at all. If you have some crazy graph of dependencies, I can see how breaking out promises could help simplify things. But I don't feel like that's a super-common scenario. The author says: > * [Promises] are easier to think about precisely because we’ve delegat…

I can speak your comment, since my side project is a Node.js server that talks to several APIs, a database, and N web clients. Like you, I've worked more than a year on it, but I had a positive experience with Q [1] and jQuery promises.

Promises make async code easy to manage, even at scale. Each API request gets its own promise. What happens inside that promise doesn't matter, as long as it returns a result or an error. If talking to the API takes one request or two, it does not matter with promises. We can abstract these API requests in such a way that even if document retrieval is a multi-step process or a one-step process for each document source, the collation process can know nothing about the retrieval process to work.

In other words, promises allow us to separate concerns. Document retrieval is one concern, collation another. Promises, by abstracting asynchronous control flow into synchronously appearing objects, allow us to write simple programs at higher levels. Separating concerns makes the server easier to test and easier to extend.

If you want to see how I've used promises, you can take a look at my work on Github [2].

[1] https://github.com/kriskowal/q

[2] https://github.com/fruchtose/muxamp

Re: Callbacks are imperative, promises are functional

#87
post #36

Earlier quoted context omitted.

Functional language has the declarative aspect while declarative language lacks the functional aspect. Just because A => B doesn't mean B => A.

You are correct that the fact that excel is declarative does not, on its own, make it "functional"... the fact that excel formulas adhere (by the definition of what an excel formula is) to the statelessness, and referential transparency requirements of "first order functions" does make it functional.

But Excel doesn't have first order functions. You can't even define a function in spreadsheet cells, let alone pass one around as a value.

Re: Callbacks are imperative, promises are functional

#88
post #13

I feel this is twisting the meaning of functional programming. Excel is not functional. It is declarative. You declare the relationships between the cells and Excel uses those to propagate changes. Just like a makefile is not functional but declarative. The dependency of the relationships are enforced to produce action. SQL is another example of declarative language and it is nowhere near as functional.

Excel is not functional. It is declarative. Alan Kay (yes, that Alan Kay[1] -- the guy that's won a Turing award) formalized spreadsheets as a limited form of first-order functional programming.[0] [0] http://en.wikipedia.org/wiki/Spreadsheet#Values [1] http://en.wikipedia.org/wiki/Alan_Kay

I'm afraid you've misunderstood that Wikipedia page. It attributes the phrase "first-order functional programming" to authors other than Kay. All it attributes to Kay is the phrase "value rule".

Kay's interest in spreadsheets wasn't about functional programming, it was about interactive and dynamic computation. I have a pdf of the 1984 Scientific American article that Wikipedia is quoting from. It does include the phrase "value rule"—by which he simply meant what we would call a spreadsheet formula—but I'm pretty sure it makes no argument about functional programming (it's all images so I can't search to be sure). If you'd like a copy, email me. It's a pretty neat article, ahead of its time as one would expect from Alan Kay.

Re: Callbacks are imperative, promises are functional

#89

It is hard for me to fathom the negative feelings towards Promises. They are quite clearly a great way to perform async programming in a civilized way (see Twitter's Future/Promise in Finagle on github). JDK 8 will even have the equivalent in CompletableFuture. The only thing better is to combine Promises with coroutines for a more linear programming style like in Flow: http://www.foundationdb.com/white-papers/flow/

if you want this on the JVM today and can abide Scala, see: http://doc.akka.io/docs/akka/snapshot/scala/dataflow.html

The Twitter solution I mention above is in Scala — that said, I have one that also works in JDK 6/7 in a branch of https://github.com/spullara/java-future-jdk8.

Re: Callbacks are imperative, promises are functional

#90
post #67

Earlier quoted context omitted.

Another point to make is that the "Excel is functional" meme is so useful is because, as soon as you tell most programmers that "functional programming" has no variables, no state, and no side-effects, they can't imagine how it's possible to actually do anything useful in a functional language. On the other hand, most programmers do know how to do useful things in a spreadsheet program- which happens to be effectivel…

That's kind of false advertisement. Excel (or spreadsheet in general) is great and easy to use because of declarative programming, not because of functional programming. The functional programming aspect of it is minimal. No variables, no state, and no side-effects are mainly attribute of declarative programming. The most important aspect of being functional, high order function, is completely missing.

Even "no variables" and "no state" are arguably untrue. The state of a spreadsheet consists of the values sitting in its cells. You mutate them by editing them.

One FP attribute that spreadsheets do have is referential transparency: the same inputs given to the same formula will always produce the same result.

Post reply on HN