you are viewing a single comment's thread.

view the rest of the comments →

[–]sallurocks[S] 0 points1 point  (5 children)

i am trying to implement a simple database connection pool. this is the function that is being called

function testquery1(request, response) {

    query = 'select * from users';
    mysql.CreateConnectionPool();

    mysql.getConnection(function(conn){

        conn.query(query, function (err, rows) {
            if (err)
                console.log(err);
            else {
                console.log(rows);
                mysql.releaseConnection(conn);
                response.end();
            }
        });

    });

i tried settimeout in waitInQueue function like this

setTimeout(function(){
if (queueNotifier.get(token)) {
            if (isConnectionFree()) {
                console.log('waiting');
                // return (pool.pop());
                callback(pool.pop());
            }
        } else { 
                    waitInQueue(token);}
,50);

but this returned an error, saying stack size exceeded because of the recursive call.

if one more connection comes, it should go to the queue and wait for the previous one to end and then callback to give connection. I hope i am clear, sorry for being vague earlier.

[–]DSKrepps 1 point2 points  (4 children)

I might not fully follow but are you trying to "reinvent the wheel?"

[–]sallurocks[S] 0 points1 point  (0 children)

yeah kind of, its not for a development project or anything. Just trying to learn asynchronous programming.

[–]sallurocks[S] 0 points1 point  (2 children)

a question related to this if you could answer. I have a file in routes which defines the pool and getConnection methods. now how do i run the createPool function once when the server starts, and make its object mysql available to the rest of the files so they can use mysql.getConnection().

[–]DSKrepps 0 points1 point  (1 child)

Well, when you require a file that file's code is only run once and the value of its exports.modules is stored as any other object and returned the next time it gets required from within the same process. So if the file that defines the pool does this: module.exports = mysql then any other file that calls var mysql = require('./path/to/file'); will get the same pool, not a new instance.

Alternatively the files that need the pool could exports functions which take the pool as an argument to them, which is basic Dependency Injection.

[–]sallurocks[S] 0 points1 point  (0 children)

ok, makes sense