Is it acceptable to call a function from a function is Node.js?

I'm learning Node.js by converting an existing Rails project. It's taken some time to get my head around callbacks and the async nature of Node.

The first general attempt looked ok, my RoR functionality was replicated and general speed was much faster using Node.

Having watched the nodecast here I started wondering whether my creation went against all the Node principals.

I have some function which, depending on the results call other functions. Simple, if, else if, else logic.

What I'm trying to figure out is if it's OK to do this or whether I should using something like the async package.

One particular function looks like this:

  checkAuthorization: function(socket,callback) {
    client.hget(socket.mac, 'authorized', function(err, val) {
      callback(val);
      if (val == null) {
        checkExteralAuth(socket.mac, socket.serial, function(val) {
          data = JSON.parse(val)
          authorized = (data["live"] == 'yep') ? true : false
          setRedisHash(socket.mac, 'authorized', authorized);
        });
      };
    });
  }

Is there a mode "node" way of doing this?

Why wouldn't it be? Node.js is a JavaScript platform. It's perfectly acceptable to call functions inside functions in a functional programming language. You do it all the time.

That said, sometimes you might want to avoid simply calling the function, especially with callbacks. The way you're calling the function, referenced by callback, implies that unless that function was explicitly bound to some context (using bind), you're losing the context.

Instead, callback.apply(this, [val]); might be the preferred way of going about your business.

Another thing is that since you're passing a callback function to be called later on, you might want to seriously look into using async as much as possible. I don't have an awful lot of experience with node.js, but by its very nature you'll find yourself writing callbacks, handlers and just using general async trickery all over the place.

Having a package that makes that job a lot easier is always handy...

There isn't anything fundamentally un-node-ish in this code, most libraries you will see are written exactly like this.

However, when you're working on an application, which tends to grow rather quickly, you eventually run into what is called the "callback hell", where the level of nesting reaches a level where you can have dozens of nested anonymous function calls.

This quickly becomes unmaintainable, which is where control flow libraries come in. There are several of the, the most popular ones being async and q.

async can be dropped readily into any codebase to manage callback hell, q requires architecting your code to work as Promises, but results in generally nicer API.