wiwengweng
wiwengweng

Reputation: 352

function done in javascript

Actually I am reading some codes in Nodejs, but I cannot get what it means because some common use of function that I don't quite understand. Can someone tell me what the function(done) means? It is a callback or something? in the js file I can't see the definition of done. Thanks

Andes

var getRedisUri = exports.getRedisUri = function (done) {
if (process.env.CLUSTER_CONFIG_URI) {
    return done(null, process.env.CLUSTER_CONFIG_URI);
}
//redis uri
Fs.readFile(
    '/opt/redis_uri',
    {encoding: 'utf8'},
    function (err, redis_uri_data) {
        if (err) {return done(err);}

        var redis_uri = redis_uri_data.toString();


        if (process.env.NODE_ENV !== 'production' &&
            process.env.VM_DOMAIN &&
            (redis_uri.indexOf('localhost') !== -1 || redis_uri.indexOf('127.0.0.1') !== -1)) {
            redis_uri = redis_uri.replace('localhost', process.env.VM_DOMAIN);
            redis_uri = redis_uri.replace('127.0.0.1', process.env.VM_DOMAIN);
        }

        done(null, redis_uri);
    });
};

Upvotes: 0

Views: 3450

Answers (1)

Raphael Serota
Raphael Serota

Reputation: 2197

That line is just the start of a function definition. function(done) just means that when this function is called, it should be called with one argument, and during the execution of the function, that argument will be referred to as done.

More specifically, I think it has to do with middleware (are you using express.js here?). If you have a bunch of middleware functions in express, the express router will call those functions for you, and pass in a function as an argument which, when called, passes the request to the next middleware function. It seems like that's what's happening here, as done gets called at the end of the function.

Node.js has stuff like this because it's all asynchronous, so you can't use return statements for much.

Upvotes: 1

Related Questions