Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of std::bind in javascript or node.js?

This is a long shot, but I was wondering if there is such a thing as the C++ std::bind in javascript or node.js? Here's the example where I felt the need for a bind:

var writeResponse = function(response, result) {
    response.write(JSON.stringify(result));
    response.end();
}


app.get('/sites', function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    dbaccess.exec(query, function(result) {
        res.write(JSON.stringify(result));
        res.end();
    });
});

Instead of passing the callback to dbaccesss.exec, I would like to pass a function pointer that takes one parameter. In C++ I would pass this:

std::bind(writeResponse, res)

This would result in a function that takes one parameter (the 'result' in my case), which I could pass instead of the anonymous callback. Right now I am duplicating all that code in the anonymous function for every route in my express app.

like image 794
cocheci Avatar asked Oct 20 '15 13:10

cocheci


1 Answers

While it exists, I'd be more inclined to do it with a closure:

function writeResponse(res) {

    return function(result) {
        res.write(JSON.stringify(result));
        res.end();
    };
}
// and then...
dbaccess.exec(query, writeResponse(res));
like image 132
chrisbajorin Avatar answered Sep 19 '22 04:09

chrisbajorin