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?
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.
fn
is a function passed as parameter to auth
.
The auth
function is called here:
Manager.prototype.authorize = function (data, fn) {
if (this.get('authorization')) {
var self = this;
this.get('authorization').call(this, data, function (err, authorized) {
self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
fn(err, authorized);
});
} else {
this.log.debug('client authorized');
fn(null, true);
}
return this;
};
So you see that the callback function accepts two parameters, err
and authorized
. In the test, those parameters are set to null
and false
.
It is likely that at some point you can specify what fn
should be, but this does not have to be! It could also be that this function is always provided by the library and it is your job to call it when you set the auth
function.
精彩评论