Is there a convention for when to use synchronous functions in Node.js?

I am making some modules in Node.js and wondered: "Is there a convention for when to use return statements in Node.js?".

From what I understand return statements should be avoided since they would make the process a blocking operation, but is there a guideline to when they should be used, and when one should stick to callbacks?

Whether something is "Blocking" or not is up to you -- does it take much time?

Any IO operation should be considered blocking, as it relies on something outside the script (which could take any amount of time).

If your own script were to say, loop over something a couple hundred times (And you know this to take more than a fraction of a second) you might consider it blocking.

  • If a method is blocking, it should accept a 'callback' parameter, and call that asynchronously.
  • If a method is non-blocking, it should not accept a 'callback' paramater, and should have at least one 'return' statement.

Your convention should simply be that you know a function is asynchronous because it accepts a callback.

If it's a "cheap" operation, that's perfectly fine. Any operations which are performed multiple times where you're not doing CPU-intensive operations can (and often should) be refactored into a "normal" function. This is fine:

function add(x, y) { return x + y; }

This is not:

function fib(n) {
    if (n <= 1) return 1;
    // this may take a long time if n is large
    return fib(n - 1) + fib (n - 2);
}

A possible implementation of fib would take a function to return the result as a parameter, and spread the calculation over multiple calls. Something like the code below, from the book "Node Web Development":

function fib(n, done) {
    if (n <= 1) {
        done(1);
    } else {
        process.nextTick(function() {
            fib(n - 1, function(val1) {
                process.nextTick(function() {
                    fib(n - 2, function(val2) {
                        done(val1 + val2);
                    });
                });
            });
        });
    }
}

Where the thread wouldn't be blocked for long.

Yes, a better alternative would be to implement fibonacci in the iterative way, not the recursive one. But this is just to demonstrate how one could "split" a CPU-heavy function.