Harry Harry - 2 months ago 7
Javascript Question

What is fn in this example?

In this example, there is an fn function with null and false arguments:

io.configure(function () {
function auth (data, fn) {
fn(null, false);
};

io.set('authorization', auth);
});


https://github.com/LearnBoost/Socket.IO-node/blob/master/test/manager.test.js#L400-403

What is
fn
and what does it do?

Does it just mean, example function, stick your own function here, or does it mean something else?

Answer

In this example, fn is a function that is passed to auth() as a parameter, so yes, you supply auth() with a bit of functionality of your own choosing. This is called a 'higher order function', see here for a short introduction. It's a technique mostly associated with functional programming, and since Javascript's object orientation is generally considered to be a bit weak, it's the style more advanced programs in Javascript tend to be in (Javascript have sometimes been called "Scheme in Java's clothing")

In this exact code: it's part of the test suite, so it configures io to always fail authorization, in order to see that an authorization failure is handled gracefully (line 408-409 for the moment):

res.statusCode.should.eql(403);
data.should.match(/handshake unauthorized/);

These lines should be reached without an exception and the tests checks that the results contain meaningful values.