Alex Alex - 11 months ago 65
Node.js Question

Passing arguments through predefined function in Node.js

I'm struggling with passing data concept in Node.js.
Let's take SQL tedious as example. Here is code from examples:

//acquire a connection
pool.acquire(function poolAcquire(err, connection) {
if (err) { console.error(err); return; }

//use the connection as normal
var request = new Request('select 1;select 2;select 3', function requestCallback (err, rowCount) {
if (err) { console.error(err); return;}

console.log('rowCount: ' + rowCount);

//release the connection back to the pool when finished
connection.release();
});

request.on('row', function onRequestRow(columns) {
console.log('value: ' + columns[0].value);
});

connection.execSql(request);
});


pool.acguire takes function as the argument and this function has particular signature (err,connection)

My question is - how do I pass SQL statement inside this function?
I cannot change signature because different function signature is not called.

Also I cannot use global scope because variable may be changed outside.

In other words I need to find way to bypass wrappers calls and still pass some data.

Something like

var mySQLs = ['select 1;select 2;select 3','select 4;select 5;'];
async.forEach(mySQLs,WorkWithOneItem, AllIsDone);

function WorkWithOneItem(item, callback){
pool.acquire(?????(item));
callback(); // tell async that the iterator has completed
}

function AllIsDone (err) {
console.log('All done');
}

Answer Source

By wrapping it in another function:

function aquire(sql, callback) {
    pool.acquire(function poolAcquire(err, connection) {
        if (err) { console.error(err); return callback(); }

        //use the connection as normal
        var request = new Request(sql, function requestCallback (err, rowCount) {
            if (err) { console.error(err); return;}

            console.log('rowCount: ' + rowCount);

            //release the connection back to the pool when finished
            connection.release();
            callback();
        });

        request.on('row', function onRequestRow(columns) {
            console.log('value: ' + columns[0].value);
        });

        connection.execSql(request);
    });
}

function WorkWithOneItem(item, callback){
    acquire(item, () => {
        callback(); // tell async that the iterator has completed
    });
}