Hacker News new | ask | show | jobs
by tlrobinson 5468 days ago
These aren't very good examples. You shouldn't break up small pieces of code just to avoid nested callbacks.

"Well, until you have two or three callbacks that respond differently to fs.readFile and you start running out of function names, right?"

That's a red flag right there. If you can't figure out a unique name for the callback, perhaps it's not worth naming it.

If you have a reusable piece of code, or it's just getting unwieldy (~3 levels deep or so), then you should consider breaking it out into it's own function. But otherwise for simple things I think it's more readable to have it inline.

It's unfortunate JavaScript's anonymous function syntax is so verbose. It would be much more pleasant with lightweight syntax (CoffeeScript, perhaps?)

4 comments

It is verbose, but on the other hand, I like the fact that the syntax for anonymous functions is pretty much almost the same as named functions.

Like what pg said somewhere (forgot where), having anonymous functions is a red flag in the language, because there shouldn't be any distinction between anonymous functions and named functions. Javascript kind of gets this right.

I believe CoffeeScript gets this even more right, by having a single way to declare functions which is also concise?

Translating the original example, sans error throws:

    fs = require 'fs'

    fs.mkdir './hello', 0777, ->
      fs.writeFile './hello/world.txt', 'Hello!', ->
        console.log 'File created with contents: '
        fs.readFile './hello/world.txt', 'UTF-8', (err, data) ->
          console.log data
The currently being worked on future version of javascript will have less verbose syntax. Brendan Eich has blogged[1] about his proposals.

Instead of

  (function(x) { return x * x })
you could just write

  #(x) { x * x }.
[1]http://brendaneich.com/2011/01/harmony-of-my-dreams/
I really like the way functions are declared in Kaffeine[1]:

  (x) { x * x }
[1] http://weepy.github.com/kaffeine/docs/function_extensions.ht...
I thought the # shorthand for functions proposal was rejected?
It was indeed. None of the function shorthands made it into ES.next, but the current leading contenders are: http://wiki.ecmascript.org/doku.php?id=strawman:arrow_functi...

    (x) -> x * x
And http://wiki.ecmascript.org/doku.php?id=strawman:block_lambda...

    {|x| x * x}
I think you make good points. The reason I used these simple examples was only for simplicity and to illustrate that named function callbacks can be used within closures rather than littering your global space with function declarations. More complex examples would probably have taken away from the core point of the article.
It's understandable you wanted simple examples, I just worry beginners will take it literally and name every callback.