NodeJS passing an extra param to a callback

NodeJS passing an extra param to a callback

Problem

I’m a begginer in Node.JS and as a first tryout i’m implementing a small url shortening service that will get a request with an id parameter and redirect to the actual url after searching a cassandra database. Below you can find my implementation.

var reqResponse;

app.get('/r/:id', function(req, res) {
    reqResponse = res;
    conn.connect(function(err, keyspace) {
        if(err){
            throw(err);
        }
        conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, redirectCallback);
    });

});

function redirectCallback (err, results) {
    if (err != null) {
        //log
    } else {
        if (results.length > 0) {
            results.every(function(row){
                reqResponse.writeHead(config.redirectStatus, {
                    'Location': row[0].value
                });
                reqResponse.end();
                return false;
            });
        } else {
            reqResponse.send("There was a problem!");
            return false;
        }
    }
    conn.close();
    return true;
}

It works fine, it does the job, but i’m having some doubts about that reqResponse “global” variable. I don’t like it there. Is there a way I could send “res” as a parameter to the redirectCallback function?

Thank you!

Problem courtesy of: maephisto

Solution

Yes there is: Create an anonymous function and use that to pass the parameter:

app.get('/r/:id', function(req, res) {
    conn.connect(function(err, keyspace) {
        if(err){
            throw(err);
        }
        conn.cql(cqlSelectStatement, [req.params.id], { gzip:true }, function (err, results) { redirectCallback(err, res, results); } );
    });

});

And your callback becomes:

function redirectCallback (err, res, results) {
Solution courtesy of: Sonata

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *